OpenTTD Source  13.1
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 #include "train_cmd.h"
38 #include "misc_cmd.h"
39 
40 #include "table/strings.h"
41 #include "table/train_sprites.h"
42 
43 #include "safeguards.h"
44 
45 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
46 static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
47 bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
49 static void CheckIfTrainNeedsService(Train *v);
50 static void CheckNextTrainTile(Train *v);
51 
52 static const byte _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
53 static const byte _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
54 
55 template <>
56 bool IsValidImageIndex<VEH_TRAIN>(uint8 image_index)
57 {
58  return image_index < lengthof(_engine_sprite_base);
59 }
60 
61 
68 {
69  if (!CargoSpec::Get(cargo)->is_freight) return 1;
71 }
72 
75 {
76  bool first = true;
77 
78  for (const Train *v : Train::Iterate()) {
79  if (v->First() == v && !(v->vehstatus & VS_CRASHED)) {
80  for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
81  if (u->track != TRACK_BIT_DEPOT) {
82  if ((w->track != TRACK_BIT_DEPOT &&
83  std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
84  (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
85  SetDParam(0, v->index);
86  SetDParam(1, v->owner);
87  ShowErrorMessage(STR_BROKEN_VEHICLE_LENGTH, INVALID_STRING_ID, WL_CRITICAL);
88 
89  if (!_networking && first) {
90  first = false;
92  }
93  /* Break so we warn only once for each train. */
94  break;
95  }
96  }
97  }
98  }
99  }
100 }
101 
109 {
110  uint16 max_speed = UINT16_MAX;
111 
112  assert(this->IsFrontEngine() || this->IsFreeWagon());
113 
114  const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
115  EngineID first_engine = this->IsFrontEngine() ? this->engine_type : INVALID_ENGINE;
116  this->gcache.cached_total_length = 0;
117  this->compatible_railtypes = RAILTYPES_NONE;
118 
119  bool train_can_tilt = true;
120  int min_curve_speed_mod = INT_MAX;
121 
122  for (Train *u = this; u != nullptr; u = u->Next()) {
123  const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
124 
125  /* Check the this->first cache. */
126  assert(u->First() == this);
127 
128  /* update the 'first engine' */
129  u->gcache.first_engine = this == u ? INVALID_ENGINE : first_engine;
130  u->railtype = rvi_u->railtype;
131 
132  if (u->IsEngine()) first_engine = u->engine_type;
133 
134  /* Set user defined data to its default value */
135  u->tcache.user_def_data = rvi_u->user_def_data;
136  this->InvalidateNewGRFCache();
137  u->InvalidateNewGRFCache();
138  }
139 
140  for (Train *u = this; u != nullptr; u = u->Next()) {
141  /* Update user defined data (must be done before other properties) */
142  u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
143  this->InvalidateNewGRFCache();
144  u->InvalidateNewGRFCache();
145  }
146 
147  for (Train *u = this; u != nullptr; u = u->Next()) {
148  const Engine *e_u = u->GetEngine();
149  const RailVehicleInfo *rvi_u = &e_u->u.rail;
150 
151  if (!HasBit(e_u->info.misc_flags, EF_RAIL_TILTS)) train_can_tilt = false;
152  min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
153 
154  /* Cache wagon override sprite group. nullptr is returned if there is none */
155  u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
156 
157  /* Reset colour map */
158  u->colourmap = PAL_NONE;
159 
160  /* Update powered-wagon-status and visual effect */
161  u->UpdateVisualEffect(true);
162 
163  if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
164  UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
165  /* wagon is powered */
166  SetBit(u->flags, VRF_POWEREDWAGON); // cache 'powered' status
167  } else {
168  ClrBit(u->flags, VRF_POWEREDWAGON);
169  }
170 
171  if (!u->IsArticulatedPart()) {
172  /* Do not count powered wagons for the compatible railtypes, as wagons always
173  have railtype normal */
174  if (rvi_u->power > 0) {
175  this->compatible_railtypes |= GetRailTypeInfo(u->railtype)->powered_railtypes;
176  }
177 
178  /* Some electric engines can be allowed to run on normal rail. It happens to all
179  * existing electric engines when elrails are disabled and then re-enabled */
180  if (HasBit(u->flags, VRF_EL_ENGINE_ALLOWED_NORMAL_RAIL)) {
181  u->railtype = RAILTYPE_RAIL;
182  u->compatible_railtypes |= RAILTYPES_RAIL;
183  }
184 
185  /* max speed is the minimum of the speed limits of all vehicles in the consist */
186  if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
187  uint16 speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
188  if (speed != 0) max_speed = std::min(speed, max_speed);
189  }
190  }
191 
192  uint16 new_cap = e_u->DetermineCapacity(u);
193  if (allowed_changes & CCF_CAPACITY) {
194  /* Update vehicle capacity. */
195  if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
196  u->refit_cap = std::min(new_cap, u->refit_cap);
197  u->cargo_cap = new_cap;
198  } else {
199  /* Verify capacity hasn't changed. */
200  if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GBUG_VEH_CAPACITY, true);
201  }
202  u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
203 
204  /* check the vehicle length (callback) */
205  uint16 veh_len = CALLBACK_FAILED;
206  if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
207  /* Use callback 36 */
208  veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
209 
210  if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
212  }
213  } else if (HasBit(e_u->info.callback_mask, CBM_VEHICLE_LENGTH)) {
214  /* Use callback 11 */
215  veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
216  }
217  if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
218  veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
219 
220  if (allowed_changes & CCF_LENGTH) {
221  /* Update vehicle length. */
222  u->gcache.cached_veh_length = veh_len;
223  } else {
224  /* Verify length hasn't changed. */
225  if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
226  }
227 
228  this->gcache.cached_total_length += u->gcache.cached_veh_length;
229  this->InvalidateNewGRFCache();
230  u->InvalidateNewGRFCache();
231  }
232 
233  /* store consist weight/max speed in cache */
234  this->vcache.cached_max_speed = max_speed;
235  this->tcache.cached_tilt = train_can_tilt;
236  this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
237  this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
238 
239  /* 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) */
240  this->CargoChanged();
241 
242  if (this->IsFrontEngine()) {
243  this->UpdateAcceleration();
247  InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
248  }
249 }
250 
261 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
262 {
263  const Station *st = Station::Get(station_id);
264  *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
265  *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
266 
267  /* Default to the middle of the station for stations stops that are not in
268  * the order list like intermediate stations when non-stop is disabled */
270  if (v->gcache.cached_total_length >= *station_length) {
271  /* The train is longer than the station, make it stop at the far end of the platform */
272  osl = OSL_PLATFORM_FAR_END;
273  } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
274  osl = v->current_order.GetStopLocation();
275  }
276 
277  /* The stop location of the FRONT! of the train */
278  int stop;
279  switch (osl) {
280  default: NOT_REACHED();
281 
283  stop = v->gcache.cached_total_length;
284  break;
285 
286  case OSL_PLATFORM_MIDDLE:
287  stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
288  break;
289 
291  stop = *station_length;
292  break;
293  }
294 
295  /* Subtract half the front vehicle length of the train so we get the real
296  * stop location of the train. */
297  return stop - (v->gcache.cached_veh_length + 1) / 2;
298 }
299 
300 
306 {
307  assert(this->First() == this);
308 
309  static const int absolute_max_speed = UINT16_MAX;
310  int max_speed = absolute_max_speed;
311 
312  if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
313 
314  int curvecount[2] = {0, 0};
315 
316  /* first find the curve speed limit */
317  int numcurve = 0;
318  int sum = 0;
319  int pos = 0;
320  int lastpos = -1;
321  for (const Vehicle *u = this; u->Next() != nullptr; u = u->Next(), pos++) {
322  Direction this_dir = u->direction;
323  Direction next_dir = u->Next()->direction;
324 
325  DirDiff dirdiff = DirDifference(this_dir, next_dir);
326  if (dirdiff == DIRDIFF_SAME) continue;
327 
328  if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
329  if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
330  if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
331  if (lastpos != -1) {
332  numcurve++;
333  sum += pos - lastpos;
334  if (pos - lastpos == 1 && max_speed > 88) {
335  max_speed = 88;
336  }
337  }
338  lastpos = pos;
339  }
340 
341  /* if we have a 90 degree turn, fix the speed limit to 60 */
342  if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
343  max_speed = 61;
344  }
345  }
346 
347  if (numcurve > 0 && max_speed > 88) {
348  if (curvecount[0] == 1 && curvecount[1] == 1) {
349  max_speed = absolute_max_speed;
350  } else {
351  sum /= numcurve;
352  max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
353  }
354  }
355 
356  if (max_speed != absolute_max_speed) {
357  /* Apply the current railtype's curve speed advantage */
358  const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
359  max_speed += (max_speed / 2) * rti->curve_speed;
360 
361  if (this->tcache.cached_tilt) {
362  /* Apply max_speed bonus of 20% for a tilting train */
363  max_speed += max_speed / 5;
364  }
365 
366  /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
367  * and clamp the result to an acceptable range. */
368  max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
369  max_speed = Clamp(max_speed, 2, absolute_max_speed);
370  }
371 
372  return max_speed;
373 }
374 
380 {
381  int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
383  this->tcache.cached_max_curve_speed;
384 
385  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
386  StationID sid = GetStationIndex(this->tile);
387  if (this->current_order.ShouldStopAtStation(this, sid)) {
388  int station_ahead;
389  int station_length;
390  int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
391 
392  /* The distance to go is whatever is still ahead of the train minus the
393  * distance from the train's stop location to the end of the platform */
394  int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
395 
396  if (distance_to_go > 0) {
397  int st_max_speed = 120;
398 
399  int delta_v = this->cur_speed / (distance_to_go + 1);
400  if (max_speed > (this->cur_speed - delta_v)) {
401  st_max_speed = this->cur_speed - (delta_v / 10);
402  }
403 
404  st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
405  max_speed = std::min(max_speed, st_max_speed);
406  }
407  }
408  }
409 
410  for (const Train *u = this; u != nullptr; u = u->Next()) {
411  if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
412  max_speed = std::min(max_speed, 61);
413  break;
414  }
415 
416  /* Vehicle is on the middle part of a bridge. */
417  if (u->track == TRACK_BIT_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
418  max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
419  }
420  }
421 
422  max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
423  return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
424 }
425 
428 {
429  assert(this->IsFrontEngine() || this->IsFreeWagon());
430 
431  uint power = this->gcache.cached_power;
432  uint weight = this->gcache.cached_weight;
433  assert(weight != 0);
434  this->acceleration = Clamp(power / weight * 4, 1, 255);
435 }
436 
437 int Train::GetCursorImageOffset() const
438 {
439  if (this->gcache.cached_veh_length != 8 && HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS)) {
440  int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
441 
442  const Engine *e = this->GetEngine();
443  if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
444  reference_width = e->GetGRF()->traininfo_vehicle_width;
445  }
446 
447  return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH);
448  }
449  return 0;
450 }
451 
458 {
459  int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
460  int vehicle_pitch = 0;
461 
462  const Engine *e = this->GetEngine();
463  if (e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
464  reference_width = e->GetGRF()->traininfo_vehicle_width;
465  vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
466  }
467 
468  if (offset != nullptr) {
469  if (HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS)) {
470  offset->x = ScaleSpriteTrad((this->gcache.cached_veh_length - VEHICLE_LENGTH / 2) * reference_width / VEHICLE_LENGTH);
471  } else {
472  offset->x = ScaleSpriteTrad(reference_width) / 2;
473  }
474  offset->y = ScaleSpriteTrad(vehicle_pitch);
475  }
476  return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
477 }
478 
479 static SpriteID GetDefaultTrainSprite(uint8 spritenum, Direction direction)
480 {
481  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
482  return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
483 }
484 
492 {
493  uint8 spritenum = this->spritenum;
494 
496 
497  if (is_custom_sprite(spritenum)) {
498  GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
499  if (result->IsValid()) return;
500 
502  }
503 
504  assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
505  SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
506 
507  if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
508 
509  result->Set(sprite);
510 }
511 
512 static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
513 {
514  const Engine *e = Engine::Get(engine);
515  Direction dir = rear_head ? DIR_E : DIR_W;
516  uint8 spritenum = e->u.rail.image_index;
517 
518  if (is_custom_sprite(spritenum)) {
519  GetCustomVehicleIcon(engine, dir, image_type, result);
520  if (result->IsValid()) {
521  if (e->GetGRF() != nullptr) {
523  }
524  return;
525  }
526 
527  spritenum = Engine::Get(engine)->original_image_index;
528  }
529 
530  if (rear_head) spritenum++;
531 
532  result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
533 }
534 
535 void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
536 {
537  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
538  int yf = y;
539  int yr = y;
540 
541  VehicleSpriteSeq seqf, seqr;
542  GetRailIcon(engine, false, yf, image_type, &seqf);
543  GetRailIcon(engine, true, yr, image_type, &seqr);
544 
545  Rect rectf, rectr;
546  seqf.GetBounds(&rectf);
547  seqr.GetBounds(&rectr);
548 
549  preferred_x = Clamp(preferred_x,
550  left - UnScaleGUI(rectf.left) + ScaleSpriteTrad(14),
551  right - UnScaleGUI(rectr.right) - ScaleSpriteTrad(15));
552 
553  seqf.Draw(preferred_x - ScaleSpriteTrad(14), yf, pal, pal == PALETTE_CRASH);
554  seqr.Draw(preferred_x + ScaleSpriteTrad(15), yr, pal, pal == PALETTE_CRASH);
555  } else {
556  VehicleSpriteSeq seq;
557  GetRailIcon(engine, false, y, image_type, &seq);
558 
559  Rect rect;
560  seq.GetBounds(&rect);
561  preferred_x = Clamp(preferred_x,
562  left - UnScaleGUI(rect.left),
563  right - UnScaleGUI(rect.right));
564 
565  seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
566  }
567 }
568 
578 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
579 {
580  int y = 0;
581 
582  VehicleSpriteSeq seq;
583  GetRailIcon(engine, false, y, image_type, &seq);
584 
585  Rect rect;
586  seq.GetBounds(&rect);
587 
588  width = UnScaleGUI(rect.Width());
589  height = UnScaleGUI(rect.Height());
590  xoffs = UnScaleGUI(rect.left);
591  yoffs = UnScaleGUI(rect.top);
592 
593  if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
594  GetRailIcon(engine, true, y, image_type, &seq);
595  seq.GetBounds(&rect);
596 
597  /* Calculate values relative to an imaginary center between the two sprites. */
598  width = ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
599  height = std::max<uint>(height, UnScaleGUI(rect.Height()));
600  xoffs = xoffs - ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
601  yoffs = std::min(yoffs, UnScaleGUI(rect.top));
602  }
603 }
604 
614 {
615  const RailVehicleInfo *rvi = &e->u.rail;
616 
617  /* Check that the wagon can drive on the track in question */
618  if (!IsCompatibleRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
619 
620  if (flags & DC_EXEC) {
621  Train *v = new Train();
622  *ret = v;
623  v->spritenum = rvi->image_index;
624 
625  v->engine_type = e->index;
626  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
627 
629 
630  v->direction = DiagDirToDir(dir);
631  v->tile = tile;
632 
633  int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
634  int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
635 
636  v->x_pos = x;
637  v->y_pos = y;
638  v->z_pos = GetSlopePixelZ(x, y);
639  v->owner = _current_company;
640  v->track = TRACK_BIT_DEPOT;
642 
643  v->SetWagon();
644 
645  v->SetFreeWagon();
647 
649  v->cargo_cap = rvi->capacity;
650  v->refit_cap = 0;
651 
652  v->railtype = rvi->railtype;
653 
655  v->build_year = _cur_year;
656  v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
658 
659  v->group_id = DEFAULT_GROUP;
660 
662 
663  v->UpdatePosition();
666 
668 
669  /* Try to connect the vehicle to one of free chains of wagons. */
670  for (Train *w : Train::Iterate()) {
671  if (w->tile == tile &&
672  w->IsFreeWagon() &&
673  w->engine_type == e->index &&
674  w->First() != v &&
675  !(w->vehstatus & VS_CRASHED)) {
676  if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, w->Last()->index, true).Succeeded()) {
677  break;
678  }
679  }
680  }
681  }
682 
683  return CommandCost();
684 }
685 
687 static void NormalizeTrainVehInDepot(const Train *u)
688 {
689  for (const Train *v : Train::Iterate()) {
690  if (v->IsFreeWagon() && v->tile == u->tile &&
691  v->track == TRACK_BIT_DEPOT) {
692  if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DC_EXEC, v->index, u->index, true).Failed()) {
693  break;
694  }
695  }
696  }
697 }
698 
699 static void AddRearEngineToMultiheadedTrain(Train *v)
700 {
701  Train *u = new Train();
702  v->value >>= 1;
703  u->value = v->value;
704  u->direction = v->direction;
705  u->owner = v->owner;
706  u->tile = v->tile;
707  u->x_pos = v->x_pos;
708  u->y_pos = v->y_pos;
709  u->z_pos = v->z_pos;
710  u->track = TRACK_BIT_DEPOT;
711  u->vehstatus = v->vehstatus & ~VS_STOPPED;
712  u->spritenum = v->spritenum + 1;
713  u->cargo_type = v->cargo_type;
715  u->cargo_cap = v->cargo_cap;
716  u->refit_cap = v->refit_cap;
717  u->railtype = v->railtype;
718  u->engine_type = v->engine_type;
720  u->build_year = v->build_year;
721  u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
723  v->SetMultiheaded();
724  u->SetMultiheaded();
725  v->SetNext(u);
726  u->UpdatePosition();
727 
728  /* Now we need to link the front and rear engines together */
729  v->other_multiheaded_part = u;
730  u->other_multiheaded_part = v;
731 }
732 
742 CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, bool free_cars, Vehicle **ret)
743 {
744  const RailVehicleInfo *rvi = &e->u.rail;
745 
746  if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(flags, tile, e, ret);
747 
748  /* Check if depot and new engine uses the same kind of tracks *
749  * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
750  if (!HasPowerOnRail(rvi->railtype, GetRailType(tile))) return CMD_ERROR;
751 
752  if (flags & DC_EXEC) {
754  int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
755  int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
756 
757  Train *v = new Train();
758  *ret = v;
759  v->direction = DiagDirToDir(dir);
760  v->tile = tile;
761  v->owner = _current_company;
762  v->x_pos = x;
763  v->y_pos = y;
764  v->z_pos = GetSlopePixelZ(x, y);
765  v->track = TRACK_BIT_DEPOT;
767  v->spritenum = rvi->image_index;
769  v->cargo_cap = rvi->capacity;
770  v->refit_cap = 0;
771  v->last_station_visited = INVALID_STATION;
772  v->last_loading_station = INVALID_STATION;
773 
774  v->engine_type = e->index;
775  v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
776 
777  v->reliability = e->reliability;
779  v->max_age = e->GetLifeLengthInDays();
780 
781  v->railtype = rvi->railtype;
782 
783  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
785  v->build_year = _cur_year;
786  v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
788 
790  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
791 
792  v->group_id = DEFAULT_GROUP;
793 
794  v->SetFrontEngine();
795  v->SetEngine();
796 
797  v->UpdatePosition();
798 
799  if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
800  AddRearEngineToMultiheadedTrain(v);
801  } else {
803  }
804 
807 
808  if (free_cars && !(flags & DC_AUTOREPLACE)) { // check if the cars should be added to the new vehicle
810  }
811 
813  }
814 
815  return CommandCost();
816 }
817 
818 static Train *FindGoodVehiclePos(const Train *src)
819 {
820  EngineID eng = src->engine_type;
821  TileIndex tile = src->tile;
822 
823  for (Train *dst : Train::Iterate()) {
824  if (dst->IsFreeWagon() && dst->tile == tile && !(dst->vehstatus & VS_CRASHED)) {
825  /* check so all vehicles in the line have the same engine. */
826  Train *t = dst;
827  while (t->engine_type == eng) {
828  t = t->Next();
829  if (t == nullptr) return dst;
830  }
831  }
832  }
833 
834  return nullptr;
835 }
836 
838 typedef std::vector<Train *> TrainList;
839 
845 static void MakeTrainBackup(TrainList &list, Train *t)
846 {
847  for (; t != nullptr; t = t->Next()) list.push_back(t);
848 }
849 
854 static void RestoreTrainBackup(TrainList &list)
855 {
856  /* No train, nothing to do. */
857  if (list.size() == 0) return;
858 
859  Train *prev = nullptr;
860  /* Iterate over the list and rebuild it. */
861  for (Train *t : list) {
862  if (prev != nullptr) {
863  prev->SetNext(t);
864  } else if (t->Previous() != nullptr) {
865  /* Make sure the head of the train is always the first in the chain. */
866  t->Previous()->SetNext(nullptr);
867  }
868  prev = t;
869  }
870 }
871 
877 static void RemoveFromConsist(Train *part, bool chain = false)
878 {
879  Train *tail = chain ? part->Last() : part->GetLastEnginePart();
880 
881  /* Unlink at the front, but make it point to the next
882  * vehicle after the to be remove part. */
883  if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
884 
885  /* Unlink at the back */
886  tail->SetNext(nullptr);
887 }
888 
894 static void InsertInConsist(Train *dst, Train *chain)
895 {
896  /* We do not want to add something in the middle of an articulated part. */
897  assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
898 
899  chain->Last()->SetNext(dst->Next());
900  dst->SetNext(chain);
901 }
902 
908 static void NormaliseDualHeads(Train *t)
909 {
910  for (; t != nullptr; t = t->GetNextVehicle()) {
911  if (!t->IsMultiheaded() || !t->IsEngine()) continue;
912 
913  /* Make sure that there are no free cars before next engine */
914  Train *u;
915  for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
916 
917  if (u == t->other_multiheaded_part) continue;
918 
919  /* Remove the part from the 'wrong' train */
920  RemoveFromConsist(t->other_multiheaded_part);
921  /* And add it to the 'right' train */
922  InsertInConsist(u, t->other_multiheaded_part);
923  }
924 }
925 
930 static void NormaliseSubtypes(Train *chain)
931 {
932  /* Nothing to do */
933  if (chain == nullptr) return;
934 
935  /* We must be the first in the chain. */
936  assert(chain->Previous() == nullptr);
937 
938  /* Set the appropriate bits for the first in the chain. */
939  if (chain->IsWagon()) {
940  chain->SetFreeWagon();
941  } else {
942  assert(chain->IsEngine());
943  chain->SetFrontEngine();
944  }
945 
946  /* Now clear the bits for the rest of the chain */
947  for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
948  t->ClearFreeWagon();
949  t->ClearFrontEngine();
950  }
951 }
952 
962 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
963 {
964  /* Just add 'new' engines and subtract the original ones.
965  * If that's less than or equal to 0 we can be sure we did
966  * not add any engines (read: trains) along the way. */
967  if ((src != nullptr && src->IsEngine() ? 1 : 0) +
968  (dst != nullptr && dst->IsEngine() ? 1 : 0) -
969  (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
970  (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
971  return CommandCost();
972  }
973 
974  /* Get a free unit number and check whether it's within the bounds.
975  * There will always be a maximum of one new train. */
977 
978  return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
979 }
980 
987 {
988  /* No multi-part train, no need to check. */
989  if (t == nullptr || t->Next() == nullptr) return CommandCost();
990 
991  /* The maximum length for a train. For each part we decrease this by one
992  * and if the result is negative the train is simply too long. */
994 
995  /* For free-wagon chains, check if they are within the max_train_length limit. */
996  if (!t->IsEngine()) {
997  t = t->Next();
998  while (t != nullptr) {
999  allowed_len -= t->gcache.cached_veh_length;
1000 
1001  t = t->Next();
1002  }
1003 
1004  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1005  return CommandCost();
1006  }
1007 
1008  Train *head = t;
1009  Train *prev = t;
1010 
1011  /* Break the prev -> t link so it always holds within the loop. */
1012  t = t->Next();
1013  prev->SetNext(nullptr);
1014 
1015  /* Make sure the cache is cleared. */
1016  head->InvalidateNewGRFCache();
1017 
1018  while (t != nullptr) {
1019  allowed_len -= t->gcache.cached_veh_length;
1020 
1021  Train *next = t->Next();
1022 
1023  /* Unlink the to-be-added piece; it is already unlinked from the previous
1024  * part due to the fact that the prev -> t link is broken. */
1025  t->SetNext(nullptr);
1026 
1027  /* Don't check callback for articulated or rear dual headed parts */
1028  if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1029  /* Back up and clear the first_engine data to avoid using wagon override group */
1030  EngineID first_engine = t->gcache.first_engine;
1032 
1033  /* We don't want the cache to interfere. head's cache is cleared before
1034  * the loop and after each callback does not need to be cleared here. */
1035  t->InvalidateNewGRFCache();
1036 
1037  uint16 callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head);
1038 
1039  /* Restore original first_engine data */
1040  t->gcache.first_engine = first_engine;
1041 
1042  /* We do not want to remember any cached variables from the test run */
1043  t->InvalidateNewGRFCache();
1044  head->InvalidateNewGRFCache();
1045 
1046  if (callback != CALLBACK_FAILED) {
1047  /* A failing callback means everything is okay */
1048  StringID error = STR_NULL;
1049 
1050  if (head->GetGRF()->grf_version < 8) {
1051  if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1052  if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1053  if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1054  } else {
1055  if (callback < 0x400) {
1056  error = GetGRFStringID(head->GetGRFID(), 0xD000 + callback);
1057  } else {
1058  switch (callback) {
1059  case 0x400: // allow if railtypes match (always the case for OpenTTD)
1060  case 0x401: // allow
1061  break;
1062 
1063  default: // unknown reason -> disallow
1064  case 0x402: // disallow attaching
1065  error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1066  break;
1067  }
1068  }
1069  }
1070 
1071  if (error != STR_NULL) return_cmd_error(error);
1072  }
1073  }
1074 
1075  /* And link it to the new part. */
1076  prev->SetNext(t);
1077  prev = t;
1078  t = next;
1079  }
1080 
1081  if (allowed_len < 0) return_cmd_error(STR_ERROR_TRAIN_TOO_LONG);
1082  return CommandCost();
1083 }
1084 
1095 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1096 {
1097  /* Check whether we may actually construct the trains. */
1098  CommandCost ret = CheckTrainAttachment(src);
1099  if (ret.Failed()) return ret;
1100  ret = CheckTrainAttachment(dst);
1101  if (ret.Failed()) return ret;
1102 
1103  /* Check whether we need to build a new train. */
1104  return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1105 }
1106 
1115 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1116 {
1117  /* First determine the front of the two resulting trains */
1118  if (*src_head == *dst_head) {
1119  /* If we aren't moving part(s) to a new train, we are just moving the
1120  * front back and there is not destination head. */
1121  *dst_head = nullptr;
1122  } else if (*dst_head == nullptr) {
1123  /* If we are moving to a new train the head of the move train would become
1124  * the head of the new vehicle. */
1125  *dst_head = src;
1126  }
1127 
1128  if (src == *src_head) {
1129  /* If we are moving the front of a train then we are, in effect, creating
1130  * a new head for the train. Point to that. Unless we are moving the whole
1131  * train in which case there is not 'source' train anymore.
1132  * In case we are a multiheaded part we want the complete thing to come
1133  * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1134  * that is followed by a rear multihead we do not want to include that. */
1135  *src_head = move_chain ? nullptr :
1136  (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1137  }
1138 
1139  /* Now it's just simply removing the part that we are going to move from the
1140  * source train and *if* the destination is a not a new train add the chain
1141  * at the destination location. */
1142  RemoveFromConsist(src, move_chain);
1143  if (*dst_head != src) InsertInConsist(dst, src);
1144 
1145  /* Now normalise the dual heads, that is move the dual heads around in such
1146  * a way that the head and rear of a dual head are in the same train */
1147  NormaliseDualHeads(*src_head);
1148  NormaliseDualHeads(*dst_head);
1149 }
1150 
1156 static void NormaliseTrainHead(Train *head)
1157 {
1158  /* Not much to do! */
1159  if (head == nullptr) return;
1160 
1161  /* Tell the 'world' the train changed. */
1162  head->ConsistChanged(CCF_ARRANGE);
1163  UpdateTrainGroupID(head);
1164 
1165  /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1166  if (!head->IsFrontEngine()) return;
1167 
1168  /* Update the refit button and window */
1171 
1172  /* If we don't have a unit number yet, set one. */
1173  if (head->unitnumber != 0) return;
1175 }
1176 
1186 CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1187 {
1188  Train *src = Train::GetIfValid(src_veh);
1189  if (src == nullptr) return CMD_ERROR;
1190 
1191  CommandCost ret = CheckOwnership(src->owner);
1192  if (ret.Failed()) return ret;
1193 
1194  /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1195  if (src->vehstatus & VS_CRASHED) return CMD_ERROR;
1196 
1197  /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1198  Train *dst;
1199  if (dest_veh == INVALID_VEHICLE) {
1200  dst = (src->IsEngine() || (flags & DC_AUTOREPLACE)) ? nullptr : FindGoodVehiclePos(src);
1201  } else {
1202  dst = Train::GetIfValid(dest_veh);
1203  if (dst == nullptr) return CMD_ERROR;
1204 
1205  CommandCost ret = CheckOwnership(dst->owner);
1206  if (ret.Failed()) return ret;
1207 
1208  /* Do not allow appending to crashed vehicles, too */
1209  if (dst->vehstatus & VS_CRASHED) return CMD_ERROR;
1210  }
1211 
1212  /* if an articulated part is being handled, deal with its parent vehicle */
1213  src = src->GetFirstEnginePart();
1214  if (dst != nullptr) {
1215  dst = dst->GetFirstEnginePart();
1216  }
1217 
1218  /* don't move the same vehicle.. */
1219  if (src == dst) return CommandCost();
1220 
1221  /* locate the head of the two chains */
1222  Train *src_head = src->First();
1223  Train *dst_head;
1224  if (dst != nullptr) {
1225  dst_head = dst->First();
1226  if (dst_head->tile != src_head->tile) return CMD_ERROR;
1227  /* Now deal with articulated part of destination wagon */
1228  dst = dst->GetLastEnginePart();
1229  } else {
1230  dst_head = nullptr;
1231  }
1232 
1233  if (src->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1234 
1235  /* When moving all wagons, we can't have the same src_head and dst_head */
1236  if (move_chain && src_head == dst_head) return CommandCost();
1237 
1238  /* When moving a multiheaded part to be place after itself, bail out. */
1239  if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1240 
1241  /* Check if all vehicles in the source train are stopped inside a depot. */
1242  if (!src_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1243 
1244  /* Check if all vehicles in the destination train are stopped inside a depot. */
1245  if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1246 
1247  /* First make a backup of the order of the trains. That way we can do
1248  * whatever we want with the order and later on easily revert. */
1249  TrainList original_src;
1250  TrainList original_dst;
1251 
1252  MakeTrainBackup(original_src, src_head);
1253  MakeTrainBackup(original_dst, dst_head);
1254 
1255  /* Also make backup of the original heads as ArrangeTrains can change them.
1256  * For the destination head we do not care if it is the same as the source
1257  * head because in that case it's just a copy. */
1258  Train *original_src_head = src_head;
1259  Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1260 
1261  /* We want this information from before the rearrangement, but execute this after the validation.
1262  * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1263  * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1264  bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1265  bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1266 
1267  /* (Re)arrange the trains in the wanted arrangement. */
1268  ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1269 
1270  if ((flags & DC_AUTOREPLACE) == 0) {
1271  /* If the autoreplace flag is set we do not need to test for the validity
1272  * because we are going to revert the train to its original state. As we
1273  * assume the original state was correct autoreplace can skip this. */
1274  CommandCost ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1275  if (ret.Failed()) {
1276  /* Restore the train we had. */
1277  RestoreTrainBackup(original_src);
1278  RestoreTrainBackup(original_dst);
1279  return ret;
1280  }
1281  }
1282 
1283  /* do it? */
1284  if (flags & DC_EXEC) {
1285  /* Remove old heads from the statistics */
1286  if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1287  if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1288 
1289  /* First normalise the sub types of the chains. */
1290  NormaliseSubtypes(src_head);
1291  NormaliseSubtypes(dst_head);
1292 
1293  /* There are 14 different cases:
1294  * 1) front engine gets moved to a new train, it stays a front engine.
1295  * a) the 'next' part is a wagon that becomes a free wagon chain.
1296  * b) the 'next' part is an engine that becomes a front engine.
1297  * c) there is no 'next' part, nothing else happens
1298  * 2) front engine gets moved to another train, it is not a front engine anymore
1299  * a) the 'next' part is a wagon that becomes a free wagon chain.
1300  * b) the 'next' part is an engine that becomes a front engine.
1301  * c) there is no 'next' part, nothing else happens
1302  * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1303  * a) the 'next' part is a wagon that becomes a free wagon chain.
1304  * b) the 'next' part is an engine that becomes a front engine.
1305  * 4) free wagon gets moved
1306  * a) the 'next' part is a wagon that becomes a free wagon chain.
1307  * b) the 'next' part is an engine that becomes a front engine.
1308  * c) there is no 'next' part, nothing else happens
1309  * 5) non front engine gets moved and becomes a new train, nothing else happens
1310  * 6) non front engine gets moved within a train / to another train, nothing happens
1311  * 7) wagon gets moved, nothing happens
1312  */
1313  if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1314  /* Cases #2 and #3: the front engine gets trashed. */
1320  DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1322 
1323  /* Delete orders, group stuff and the unit number as we're not the
1324  * front of any vehicle anymore. */
1325  DeleteVehicleOrders(src);
1327  src->unitnumber = 0;
1328  }
1329 
1330  /* We weren't a front engine but are becoming one. So
1331  * we should be put in the default group. */
1332  if (original_src_head != src && dst_head == src) {
1335  }
1336 
1337  /* Add new heads to statistics */
1338  if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1339  if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1340 
1341  /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1342  NormaliseTrainHead(src_head);
1343  NormaliseTrainHead(dst_head);
1344 
1345  if ((flags & DC_NO_CARGO_CAP_CHECK) == 0) {
1346  CheckCargoCapacity(src_head);
1347  CheckCargoCapacity(dst_head);
1348  }
1349 
1350  if (src_head != nullptr) src_head->First()->MarkDirty();
1351  if (dst_head != nullptr) dst_head->First()->MarkDirty();
1352 
1353  /* We are undoubtedly changing something in the depot and train list. */
1356  } else {
1357  /* We don't want to execute what we're just tried. */
1358  RestoreTrainBackup(original_src);
1359  RestoreTrainBackup(original_dst);
1360  }
1361 
1362  return CommandCost();
1363 }
1364 
1377 CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1378 {
1380  Train *first = v->First();
1381 
1382  if (v->IsRearDualheaded()) return_cmd_error(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1383 
1384  /* First make a backup of the order of the train. That way we can do
1385  * whatever we want with the order and later on easily revert. */
1386  TrainList original;
1387  MakeTrainBackup(original, first);
1388 
1389  /* We need to keep track of the new head and the head of what we're going to sell. */
1390  Train *new_head = first;
1391  Train *sell_head = nullptr;
1392 
1393  /* Split the train in the wanted way. */
1394  ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1395 
1396  /* We don't need to validate the second train; it's going to be sold. */
1397  CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, (flags & DC_AUTOREPLACE) == 0);
1398  if (ret.Failed()) {
1399  /* Restore the train we had. */
1400  RestoreTrainBackup(original);
1401  return ret;
1402  }
1403 
1404  if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1405  /* Restore the train we had. */
1406  RestoreTrainBackup(original);
1407  return_cmd_error(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1408  }
1409 
1411  for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1412 
1413  /* do it? */
1414  if (flags & DC_EXEC) {
1415  /* First normalise the sub types of the chain. */
1416  NormaliseSubtypes(new_head);
1417 
1418  if (v == first && v->IsEngine() && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1419  /* We are selling the front engine. In this case we want to
1420  * 'give' the order, unit number and such to the new head. */
1421  new_head->orders = first->orders;
1422  new_head->AddToShared(first);
1424 
1425  /* Copy other important data from the front engine */
1427  GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit
1428  } else if (v->IsPrimaryVehicle() && backup_order) {
1429  OrderBackup::Backup(v, user);
1430  }
1431 
1432  /* We need to update the information about the train. */
1433  NormaliseTrainHead(new_head);
1434 
1435  /* We are undoubtedly changing something in the depot and train list. */
1438 
1439  /* Actually delete the sold 'goods' */
1440  delete sell_head;
1441  } else {
1442  /* We don't want to execute what we're just tried. */
1443  RestoreTrainBackup(original);
1444  }
1445 
1446  return cost;
1447 }
1448 
1450 {
1451  /* Set common defaults. */
1452  this->x_offs = -1;
1453  this->y_offs = -1;
1454  this->x_extent = 3;
1455  this->y_extent = 3;
1456  this->z_extent = 6;
1457  this->x_bb_offs = 0;
1458  this->y_bb_offs = 0;
1459 
1460  /* Set if flipped and engine is NOT flagged with custom flip handling. */
1461  int flipped = HasBit(this->flags, VRF_REVERSE_DIRECTION) && !HasBit(EngInfo(this->engine_type)->misc_flags, EF_RAIL_FLIPS);
1462  /* If flipped and vehicle length is odd, we need to adjust the bounding box offset slightly. */
1463  int flip_offs = flipped && (this->gcache.cached_veh_length & 1);
1464 
1465  Direction dir = this->direction;
1466  if (flipped) dir = ReverseDir(dir);
1467 
1468  if (!IsDiagonalDirection(dir)) {
1469  static const int _sign_table[] =
1470  {
1471  /* x, y */
1472  -1, -1, // DIR_N
1473  -1, 1, // DIR_E
1474  1, 1, // DIR_S
1475  1, -1, // DIR_W
1476  };
1477 
1478  int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length + flipped) / 2;
1479 
1480  /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1481  this->x_offs -= half_shorten * _sign_table[dir];
1482  this->y_offs -= half_shorten * _sign_table[dir + 1];
1483  this->x_extent += this->x_bb_offs = half_shorten * _sign_table[dir];
1484  this->y_extent += this->y_bb_offs = half_shorten * _sign_table[dir + 1];
1485  } else {
1486  switch (dir) {
1487  /* Shorten southern corner of the bounding box according the vehicle length
1488  * and center the bounding box on the vehicle. */
1489  case DIR_NE:
1490  this->x_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1491  this->x_extent = this->gcache.cached_veh_length - 1;
1492  this->x_bb_offs = -1;
1493  break;
1494 
1495  case DIR_NW:
1496  this->y_offs = 1 - (this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1497  this->y_extent = this->gcache.cached_veh_length - 1;
1498  this->y_bb_offs = -1;
1499  break;
1500 
1501  /* Move northern corner of the bounding box down according to vehicle length
1502  * and center the bounding box on the vehicle. */
1503  case DIR_SW:
1504  this->x_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1505  this->x_extent = VEHICLE_LENGTH - 1;
1506  this->x_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1507  break;
1508 
1509  case DIR_SE:
1510  this->y_offs = 1 + (this->gcache.cached_veh_length + 1) / 2 - VEHICLE_LENGTH - flip_offs;
1511  this->y_extent = VEHICLE_LENGTH - 1;
1512  this->y_bb_offs = VEHICLE_LENGTH - this->gcache.cached_veh_length - 1;
1513  break;
1514 
1515  default:
1516  NOT_REACHED();
1517  }
1518  }
1519 }
1520 
1525 static void MarkTrainAsStuck(Train *v)
1526 {
1527  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) {
1528  /* It is the first time the problem occurred, set the "train stuck" flag. */
1529  SetBit(v->flags, VRF_TRAIN_STUCK);
1530 
1531  v->wait_counter = 0;
1532 
1533  /* Stop train */
1534  v->cur_speed = 0;
1535  v->subspeed = 0;
1536  v->SetLastSpeed();
1537 
1539  }
1540 }
1541 
1549 static void SwapTrainFlags(uint16 *swap_flag1, uint16 *swap_flag2)
1550 {
1551  uint16 flag1 = *swap_flag1;
1552  uint16 flag2 = *swap_flag2;
1553 
1554  /* Clear the flags */
1555  ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1556  ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1557  ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1558  ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1559 
1560  /* Reverse the rail-flags (if needed) */
1561  if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1562  SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1563  } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1564  SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1565  }
1566  if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1567  SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1568  } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1569  SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1570  }
1571 }
1572 
1578 {
1579  /* Reverse the direction. */
1580  if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1581 
1582  /* Call the proper EnterTile function unless we are in a wormhole. */
1583  if (v->track != TRACK_BIT_WORMHOLE) {
1584  VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1585  } else {
1586  /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1587  * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1588  * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1589  * when we shouldn't have. Check if this is the case. */
1590  TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1591  if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1592  VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1593  if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1594  /* We have just left the wormhole, possibly set the
1595  * "goingdown" bit. UpdateInclination() can be used
1596  * because we are at the border of the tile. */
1597  v->UpdatePosition();
1598  v->UpdateInclination(true, true);
1599  return;
1600  }
1601  }
1602  }
1603 
1604  v->UpdatePosition();
1605  v->UpdateViewport(true, true);
1606 }
1607 
1614 void ReverseTrainSwapVeh(Train *v, int l, int r)
1615 {
1616  Train *a, *b;
1617 
1618  /* locate vehicles to swap */
1619  for (a = v; l != 0; l--) a = a->Next();
1620  for (b = v; r != 0; r--) b = b->Next();
1621 
1622  if (a != b) {
1623  /* swap the hidden bits */
1624  {
1625  uint16 tmp = (a->vehstatus & ~VS_HIDDEN) | (b->vehstatus & VS_HIDDEN);
1626  b->vehstatus = (b->vehstatus & ~VS_HIDDEN) | (a->vehstatus & VS_HIDDEN);
1627  a->vehstatus = tmp;
1628  }
1629 
1630  Swap(a->track, b->track);
1631  Swap(a->direction, b->direction);
1632  Swap(a->x_pos, b->x_pos);
1633  Swap(a->y_pos, b->y_pos);
1634  Swap(a->tile, b->tile);
1635  Swap(a->z_pos, b->z_pos);
1636 
1637  SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1638 
1641  } else {
1642  /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1643  * This is a little bit redundant way, a->gv_flags will
1644  * be (re)set twice, but it reduces code duplication */
1645  SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1647  }
1648 }
1649 
1650 
1656 static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
1657 {
1658  return (v->type == VEH_TRAIN) ? v : nullptr;
1659 }
1660 
1668 {
1669  assert(IsLevelCrossingTile(tile));
1670 
1671  return HasVehicleOnPos(tile, nullptr, &TrainOnTileEnum);
1672 }
1673 
1674 
1682 {
1683  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
1684 
1685  Train *t = Train::From(v);
1686  if (!t->IsFrontEngine()) return nullptr;
1687 
1688  TileIndex tile = *(TileIndex *)data;
1689 
1690  if (TrainApproachingCrossingTile(t) != tile) return nullptr;
1691 
1692  return t;
1693 }
1694 
1695 
1703 {
1704  assert(IsLevelCrossingTile(tile));
1705 
1707  TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1708 
1709  if (HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum)) return true;
1710 
1711  dir = ReverseDiagDir(dir);
1712  tile_from = tile + TileOffsByDiagDir(dir);
1713 
1714  return HasVehicleOnPos(tile_from, &tile, &TrainApproachingCrossingEnum);
1715 }
1716 
1722 static inline bool CheckLevelCrossing(TileIndex tile)
1723 {
1724  /* reserved || train on crossing || train approaching crossing */
1726 }
1727 
1735 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1736 {
1737  assert(IsLevelCrossingTile(tile));
1738  bool set_barred;
1739 
1740  /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1741  set_barred = force_barred || CheckLevelCrossing(tile);
1742 
1743  /* The state has changed */
1744  if (set_barred != IsCrossingBarred(tile)) {
1745  if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1746  SetCrossingBarred(tile, set_barred);
1748  }
1749 }
1750 
1757 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1758 {
1759  if (!IsLevelCrossingTile(tile)) return;
1760 
1761  bool forced_state = force_bar;
1762 
1763  const Axis axis = GetCrossingRoadAxis(tile);
1764  const DiagDirection dir1 = AxisToDiagDir(axis);
1765  const DiagDirection dir2 = ReverseDiagDir(dir1);
1766 
1767  /* Check if an adjacent crossing is barred. */
1768  for (DiagDirection dir : { dir1, dir2 }) {
1769  for (TileIndex t = tile; !forced_state && t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1770  forced_state |= CheckLevelCrossing(t);
1771  }
1772  }
1773 
1774  /* Now that we know whether all tiles in this crossing should be barred or open,
1775  * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1776  UpdateLevelCrossingTile(tile, sound, forced_state);
1777  for (DiagDirection dir : { dir1, dir2 }) {
1778  for (TileIndex t = TileAddByDiagDir(tile, dir); t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1779  UpdateLevelCrossingTile(t, sound, forced_state);
1780  }
1781  }
1782 }
1783 
1789 {
1790  const DiagDirection dir1 = AxisToDiagDir(road_axis);
1791  const DiagDirection dir2 = ReverseDiagDir(dir1);
1792  for (DiagDirection dir : { dir1, dir2 }) {
1793  const TileIndex t = TileAddByDiagDir(tile, dir);
1794  if (t < MapSize() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1796  }
1797  }
1798 }
1799 
1806 {
1807  if (!IsCrossingBarred(tile)) {
1809  UpdateLevelCrossing(tile, true);
1810  }
1811 }
1812 
1813 
1820 {
1821  Train *base = v;
1822  Train *first = base; // first vehicle to move
1823  Train *last = v->Last(); // last vehicle to move
1824  uint length = CountVehiclesInChain(v);
1825 
1826  while (length > 2) {
1827  last = last->Previous();
1828  first = first->Next();
1829 
1830  int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1831 
1832  /* do not update images now
1833  * negative differential will be handled in AdvanceWagonsAfterSwap() */
1834  for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1835 
1836  base = first; // == base->Next()
1837  length -= 2;
1838  }
1839 }
1840 
1841 
1848 {
1849  /* first of all, fix the situation when the train was entering a depot */
1850  Train *dep = v; // last vehicle in front of just left depot
1851  while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1852  dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1853  }
1854 
1855  Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1856 
1857  if (leave != nullptr) {
1858  /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1859  int d = TicksToLeaveDepot(dep);
1860 
1861  if (d <= 0) {
1862  leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
1863  leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1864  for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1865  }
1866  } else {
1867  dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1868  }
1869 
1870  Train *base = v;
1871  Train *first = base; // first vehicle to move
1872  Train *last = v->Last(); // last vehicle to move
1873  uint length = CountVehiclesInChain(v);
1874 
1875  /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1876  * they have already correct spacing, so we have to make sure they are moved how they should */
1877  bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1878 
1879  while (length > 2) {
1880  /* we reached vehicle (originally) in front of a depot, stop now
1881  * (we would move wagons that are already moved with new wagon length). */
1882  if (base == dep) break;
1883 
1884  /* the last wagon was that one leaving a depot, so do not move it anymore */
1885  if (last == dep) nomove = true;
1886 
1887  last = last->Previous();
1888  first = first->Next();
1889 
1890  int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1891 
1892  /* do not update images now */
1893  for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1894 
1895  base = first; // == base->Next()
1896  length -= 2;
1897  }
1898 }
1899 
1900 static bool IsWholeTrainInsideDepot(const Train *v)
1901 {
1902  for (const Train *u = v; u != nullptr; u = u->Next()) {
1903  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1904  }
1905  return true;
1906 }
1907 
1913 {
1914  if (IsRailDepotTile(v->tile)) {
1915  if (IsWholeTrainInsideDepot(v)) return;
1917  }
1918 
1919  /* Clear path reservation in front if train is not stuck. */
1920  if (!HasBit(v->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(v);
1921 
1922  /* Check if we were approaching a rail/road-crossing */
1924 
1925  /* count number of vehicles */
1926  int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
1927 
1929 
1930  /* swap start<>end, start+1<>end-1, ... */
1931  int l = 0;
1932  do {
1933  ReverseTrainSwapVeh(v, l++, r--);
1934  } while (l <= r);
1935 
1937 
1938  if (IsRailDepotTile(v->tile)) {
1940  }
1941 
1942  ToggleBit(v->flags, VRF_TOGGLE_REVERSE);
1943 
1944  ClrBit(v->flags, VRF_REVERSING);
1945 
1946  /* recalculate cached data */
1948 
1949  /* update all images */
1950  for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
1951 
1952  /* update crossing we were approaching */
1953  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
1954 
1955  /* maybe we are approaching crossing now, after reversal */
1956  crossing = TrainApproachingCrossingTile(v);
1957  if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
1958 
1959  /* If we are inside a depot after reversing, don't bother with path reserving. */
1960  if (v->track == TRACK_BIT_DEPOT) {
1961  /* Can't be stuck here as inside a depot is always a safe tile. */
1963  ClrBit(v->flags, VRF_TRAIN_STUCK);
1964  return;
1965  }
1966 
1967  /* VehicleExitDir does not always produce the desired dir for depots and
1968  * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
1969  DiagDirection dir = VehicleExitDir(v->direction, v->track);
1971 
1973  /* If we are currently on a tile with conventional signals, we can't treat the
1974  * current tile as a safe tile or we would enter a PBS block without a reservation. */
1975  bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
1977  !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
1978 
1979  /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
1980  if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
1981 
1983  if (TryPathReserve(v, false, first_tile_okay)) {
1984  /* Do a look-ahead now in case our current tile was already a safe tile. */
1985  CheckNextTrainTile(v);
1986  } else if (v->current_order.GetType() != OT_LOADING) {
1987  /* Do not wait for a way out when we're still loading */
1988  MarkTrainAsStuck(v);
1989  }
1990  } else if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
1991  /* A train not inside a PBS block can't be stuck. */
1992  ClrBit(v->flags, VRF_TRAIN_STUCK);
1993  v->wait_counter = 0;
1994  }
1995 }
1996 
2004 CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
2005 {
2006  Train *v = Train::GetIfValid(veh_id);
2007  if (v == nullptr) return CMD_ERROR;
2008 
2009  CommandCost ret = CheckOwnership(v->owner);
2010  if (ret.Failed()) return ret;
2011 
2012  if (reverse_single_veh) {
2013  /* turn a single unit around */
2014 
2015  if (v->IsMultiheaded() || HasBit(EngInfo(v->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) {
2016  return_cmd_error(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2017  }
2018 
2019  Train *front = v->First();
2020  /* make sure the vehicle is stopped in the depot */
2021  if (!front->IsStoppedInDepot()) {
2022  return_cmd_error(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2023  }
2024 
2025  if (flags & DC_EXEC) {
2026  ToggleBit(v->flags, VRF_REVERSE_DIRECTION);
2027 
2028  front->ConsistChanged(CCF_ARRANGE);
2033  }
2034  } else {
2035  /* turn the whole train around */
2036  if (!v->IsPrimaryVehicle()) return CMD_ERROR;
2037  if ((v->vehstatus & VS_CRASHED) || v->breakdown_ctr != 0) return CMD_ERROR;
2038 
2039  if (flags & DC_EXEC) {
2040  /* Properly leave the station if we are loading and won't be loading anymore */
2041  if (v->current_order.IsType(OT_LOADING)) {
2042  const Vehicle *last = v;
2043  while (last->Next() != nullptr) last = last->Next();
2044 
2045  /* not a station || different station --> leave the station */
2046  if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2047  v->LeaveStation();
2048  }
2049  }
2050 
2051  /* We cancel any 'skip signal at dangers' here */
2052  v->force_proceed = TFP_NONE;
2054 
2055  if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2056  ToggleBit(v->flags, VRF_REVERSING);
2057  } else {
2058  v->cur_speed = 0;
2059  v->SetLastSpeed();
2062  }
2063  }
2064  }
2065  return CommandCost();
2066 }
2067 
2075 {
2076  Train *t = Train::GetIfValid(veh_id);
2077  if (t == nullptr) return CMD_ERROR;
2078 
2079  if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2080 
2081  CommandCost ret = CheckOwnership(t->owner);
2082  if (ret.Failed()) return ret;
2083 
2084 
2085  if (flags & DC_EXEC) {
2086  /* If we are forced to proceed, cancel that order.
2087  * If we are marked stuck we would want to force the train
2088  * to proceed to the next signal. In the other cases we
2089  * would like to pass the signal at danger and run till the
2090  * next signal we encounter. */
2091  t->force_proceed = t->force_proceed == TFP_SIGNAL ? TFP_NONE : HasBit(t->flags, VRF_TRAIN_STUCK) || t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2093  }
2094 
2095  return CommandCost();
2096 }
2097 
2105 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2106 {
2107  assert(!(v->vehstatus & VS_CRASHED));
2108 
2109  if (IsRailDepotTile(v->tile)) return FindDepotData(v->tile, 0);
2110 
2111  PBSTileInfo origin = FollowTrainReservation(v);
2112  if (IsRailDepotTile(origin.tile)) return FindDepotData(origin.tile, 0);
2113 
2115  case VPF_NPF: return NPFTrainFindNearestDepot(v, max_distance);
2116  case VPF_YAPF: return YapfTrainFindNearestDepot(v, max_distance);
2117 
2118  default: NOT_REACHED();
2119  }
2120 }
2121 
2129 bool Train::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
2130 {
2131  FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2132  if (tfdd.best_length == UINT_MAX) return false;
2133 
2134  if (location != nullptr) *location = tfdd.tile;
2135  if (destination != nullptr) *destination = GetDepotIndex(tfdd.tile);
2136  if (reverse != nullptr) *reverse = tfdd.reverse;
2137 
2138  return true;
2139 }
2140 
2142 void Train::PlayLeaveStationSound(bool force) const
2143 {
2144  static const SoundFx sfx[] = {
2150  };
2151 
2152  if (PlayVehicleSound(this, VSE_START, force)) return;
2153 
2154  SndPlayVehicleFx(sfx[RailVehInfo(this->engine_type)->engclass], this);
2155 }
2156 
2161 static void CheckNextTrainTile(Train *v)
2162 {
2163  /* Don't do any look-ahead if path_backoff_interval is 255. */
2164  if (_settings_game.pf.path_backoff_interval == 255) return;
2165 
2166  /* Exit if we are inside a depot. */
2167  if (v->track == TRACK_BIT_DEPOT) return;
2168 
2169  switch (v->current_order.GetType()) {
2170  /* Exit if we reached our destination depot. */
2171  case OT_GOTO_DEPOT:
2172  if (v->tile == v->dest_tile) return;
2173  break;
2174 
2175  case OT_GOTO_WAYPOINT:
2176  /* If we reached our waypoint, make sure we see that. */
2178  break;
2179 
2180  case OT_NOTHING:
2181  case OT_LEAVESTATION:
2182  case OT_LOADING:
2183  /* Exit if the current order doesn't have a destination, but the train has orders. */
2184  if (v->GetNumOrders() > 0) return;
2185  break;
2186 
2187  default:
2188  break;
2189  }
2190  /* Exit if we are on a station tile and are going to stop. */
2192 
2193  Trackdir td = v->GetVehicleTrackdir();
2194 
2195  /* On a tile with a red non-pbs signal, don't look ahead. */
2196  if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2197  !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2198  GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2199 
2200  CFollowTrackRail ft(v);
2201  if (!ft.Follow(v->tile, td)) return;
2202 
2204  /* Next tile is not reserved. */
2207  /* If the next tile is a PBS signal, try to make a reservation. */
2211  }
2212  ChooseTrainTrack(v, ft.m_new_tile, ft.m_exitdir, tracks, false, nullptr, false);
2213  }
2214  }
2215  }
2216 }
2217 
2224 {
2225  /* bail out if not all wagons are in the same depot or not in a depot at all */
2226  for (const Train *u = v; u != nullptr; u = u->Next()) {
2227  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2228  }
2229 
2230  /* if the train got no power, then keep it in the depot */
2231  if (v->gcache.cached_power == 0) {
2232  v->vehstatus |= VS_STOPPED;
2234  return true;
2235  }
2236 
2237  SigSegState seg_state;
2238 
2239  if (v->force_proceed == TFP_NONE) {
2240  /* force proceed was not pressed */
2241  if (++v->wait_counter < 37) {
2243  return true;
2244  }
2245 
2246  v->wait_counter = 0;
2247 
2249  if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2250  /* Full and no PBS signal in block or depot reserved, can't exit. */
2252  return true;
2253  }
2254  } else {
2256  }
2257 
2258  /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2259  if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2260  /* Service when depot has no reservation. */
2262  return true;
2263  }
2264 
2265  /* Only leave when we can reserve a path to our destination. */
2266  if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2267  /* No path and no force proceed. */
2269  MarkTrainAsStuck(v);
2270  return true;
2271  }
2272 
2273  SetDepotReservation(v->tile, true);
2275 
2278  v->PlayLeaveStationSound();
2279 
2280  v->track = TRACK_BIT_X;
2281  if (v->direction & 2) v->track = TRACK_BIT_Y;
2282 
2283  v->vehstatus &= ~VS_HIDDEN;
2284  v->cur_speed = 0;
2285 
2286  v->UpdateViewport(true, true);
2287  v->UpdatePosition();
2289  v->UpdateAcceleration();
2291 
2292  return false;
2293 }
2294 
2301 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2302 {
2303  DiagDirection dir = TrackdirToExitdir(track_dir);
2304 
2306  /* Are we just leaving a tunnel/bridge? */
2309 
2310  if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2311  /* Free the reservation only if no other train is on the tiles. */
2313  SetTunnelBridgeReservation(end, false);
2314 
2316  if (IsBridge(tile)) {
2318  } else {
2320  MarkTileDirtyByTile(end);
2321  }
2322  }
2323  }
2324  }
2325  } else if (IsRailStationTile(tile)) {
2326  TileIndex new_tile = TileAddByDiagDir(tile, dir);
2327  /* If the new tile is not a further tile of the same station, we
2328  * clear the reservation for the whole platform. */
2329  if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2331  }
2332  } else {
2333  /* Any other tile */
2335  }
2336 }
2337 
2343 {
2344  assert(v->IsFrontEngine());
2345 
2346  TileIndex tile = v->tile;
2347  Trackdir td = v->GetVehicleTrackdir();
2348  bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2349  StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : INVALID_STATION;
2350 
2351  /* Can't be holding a reservation if we enter a depot. */
2353  if (v->track == TRACK_BIT_DEPOT) {
2354  /* Front engine is in a depot. We enter if some part is not in the depot. */
2355  for (const Train *u = v; u != nullptr; u = u->Next()) {
2356  if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2357  }
2358  }
2359  /* Don't free reservation if it's not ours. */
2361 
2363  while (ft.Follow(tile, td)) {
2364  tile = ft.m_new_tile;
2366  td = RemoveFirstTrackdir(&bits);
2367  assert(bits == TRACKDIR_BIT_NONE);
2368 
2369  if (!IsValidTrackdir(td)) break;
2370 
2371  if (IsTileType(tile, MP_RAILWAY)) {
2372  if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2373  /* Conventional signal along trackdir: remove reservation and stop. */
2375  break;
2376  }
2377  if (HasPbsSignalOnTrackdir(tile, td)) {
2379  /* Red PBS signal? Can't be our reservation, would be green then. */
2380  break;
2381  } else {
2382  /* Turn the signal back to red. */
2385  }
2387  break;
2388  }
2389  }
2390 
2391  /* Don't free first station/bridge/tunnel if we are on it. */
2392  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);
2393 
2394  free_tile = true;
2395  }
2396 }
2397 
2398 static const byte _initial_tile_subcoord[6][4][3] = {
2399 {{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2400 {{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2401 {{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2402 {{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2403 {{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2404 {{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2405 };
2406 
2420 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2421 {
2422  if (final_dest != nullptr) *final_dest = INVALID_TILE;
2423 
2425  case VPF_NPF: return NPFTrainChooseTrack(v, path_found, do_track_reservation, dest);
2426  case VPF_YAPF: return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2427 
2428  default: NOT_REACHED();
2429  }
2430 }
2431 
2437 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2438 {
2439  PBSTileInfo origin = FollowTrainReservation(v);
2440 
2441  CFollowTrackRail ft(v);
2442 
2443  TileIndex tile = origin.tile;
2444  Trackdir cur_td = origin.trackdir;
2445  while (ft.Follow(tile, cur_td)) {
2447  /* Possible signal tile. */
2449  }
2450 
2453  if (ft.m_new_td_bits == TRACKDIR_BIT_NONE) break;
2454  }
2455 
2456  /* Station, depot or waypoint are a possible target. */
2457  bool target_seen = ft.m_is_station || (IsTileType(ft.m_new_tile, MP_RAILWAY) && !IsPlainRail(ft.m_new_tile));
2458  if (target_seen || KillFirstBit(ft.m_new_td_bits) != TRACKDIR_BIT_NONE) {
2459  /* Choice found or possible target encountered.
2460  * On finding a possible target, we need to stop and let the pathfinder handle the
2461  * remaining path. This is because we don't know if this target is in one of our
2462  * orders, so we might cause pathfinding to fail later on if we find a choice.
2463  * This failure would cause a bogous call to TryReserveSafePath which might reserve
2464  * a wrong path not leading to our next destination. */
2466 
2467  /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2468  * actually starts its search at the first unreserved tile. */
2470 
2471  /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2472  if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.m_new_td_bits);
2473  if (enterdir != nullptr) *enterdir = ft.m_exitdir;
2474  return PBSTileInfo(ft.m_new_tile, ft.m_old_td, false);
2475  }
2476 
2477  tile = ft.m_new_tile;
2478  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2479 
2480  if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2481  bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2482  if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2483  /* Safe position is all good, path valid and okay. */
2484  return PBSTileInfo(tile, cur_td, true);
2485  }
2486 
2487  if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2488  }
2489 
2490  if (ft.m_err == CFollowTrackRail::EC_OWNER || ft.m_err == CFollowTrackRail::EC_NO_WAY) {
2491  /* End of line, path valid and okay. */
2492  return PBSTileInfo(ft.m_old_tile, ft.m_old_td, true);
2493  }
2494 
2495  /* Sorry, can't reserve path, back out. */
2496  tile = origin.tile;
2497  cur_td = origin.trackdir;
2498  TileIndex stopped = ft.m_old_tile;
2499  Trackdir stopped_td = ft.m_old_td;
2500  while (tile != stopped || cur_td != stopped_td) {
2501  if (!ft.Follow(tile, cur_td)) break;
2502 
2505  assert(ft.m_new_td_bits != TRACKDIR_BIT_NONE);
2506  }
2508 
2509  tile = ft.m_new_tile;
2510  cur_td = FindFirstTrackdir(ft.m_new_td_bits);
2511 
2513  }
2514 
2515  /* Path invalid. */
2516  return PBSTileInfo();
2517 }
2518 
2529 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2530 {
2532  case VPF_NPF: return NPFTrainFindNearestSafeTile(v, tile, td, override_railtype);
2533  case VPF_YAPF: return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2534 
2535  default: NOT_REACHED();
2536  }
2537 }
2538 
2541 private:
2542  Train *v;
2543  Order old_order;
2544  TileIndex old_dest_tile;
2545  StationID old_last_station_visited;
2546  VehicleOrderID index;
2547  bool suppress_implicit_orders;
2548  bool restored;
2549 
2550 public:
2551  VehicleOrderSaver(Train *_v) :
2552  v(_v),
2553  old_order(_v->current_order),
2554  old_dest_tile(_v->dest_tile),
2555  old_last_station_visited(_v->last_station_visited),
2556  index(_v->cur_real_order_index),
2557  suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS)),
2558  restored(false)
2559  {
2560  }
2561 
2565  void Restore()
2566  {
2567  this->v->current_order = this->old_order;
2568  this->v->dest_tile = this->old_dest_tile;
2569  this->v->last_station_visited = this->old_last_station_visited;
2570  SB(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, 1, suppress_implicit_orders ? 1: 0);
2571  this->restored = true;
2572  }
2573 
2578  {
2579  if (!this->restored) this->Restore();
2580  }
2581 
2587  bool SwitchToNextOrder(bool skip_first)
2588  {
2589  if (this->v->GetNumOrders() == 0) return false;
2590 
2591  if (skip_first) ++this->index;
2592 
2593  int depth = 0;
2594 
2595  do {
2596  /* Wrap around. */
2597  if (this->index >= this->v->GetNumOrders()) this->index = 0;
2598 
2599  Order *order = this->v->GetOrder(this->index);
2600  assert(order != nullptr);
2601 
2602  switch (order->GetType()) {
2603  case OT_GOTO_DEPOT:
2604  /* Skip service in depot orders when the train doesn't need service. */
2605  if ((order->GetDepotOrderType() & ODTFB_SERVICE) && !this->v->NeedsServicing()) break;
2606  FALLTHROUGH;
2607  case OT_GOTO_STATION:
2608  case OT_GOTO_WAYPOINT:
2609  this->v->current_order = *order;
2610  return UpdateOrderDest(this->v, order, 0, true);
2611  case OT_CONDITIONAL: {
2612  VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2613  if (next != INVALID_VEH_ORDER_ID) {
2614  depth++;
2615  this->index = next;
2616  /* Don't increment next, so no break here. */
2617  continue;
2618  }
2619  break;
2620  }
2621  default:
2622  break;
2623  }
2624  /* Don't increment inside the while because otherwise conditional
2625  * orders can lead to an infinite loop. */
2626  ++this->index;
2627  depth++;
2628  } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2629 
2630  return false;
2631  }
2632 };
2633 
2634 /* choose a track */
2635 static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2636 {
2637  Track best_track = INVALID_TRACK;
2638  bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2639  bool changed_signal = false;
2640  TileIndex final_dest = INVALID_TILE;
2641 
2642  assert((tracks & ~TRACK_BIT_MASK) == 0);
2643 
2644  if (got_reservation != nullptr) *got_reservation = false;
2645 
2646  /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2647  TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2648  /* Do we have a suitable reserved track? */
2649  if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2650 
2651  /* Quick return in case only one possible track is available */
2652  if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2653  Track track = FindFirstTrack(tracks);
2654  /* We need to check for signals only here, as a junction tile can't have signals. */
2655  if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2656  do_track_reservation = true;
2657  changed_signal = true;
2659  } else if (!do_track_reservation) {
2660  return track;
2661  }
2662  best_track = track;
2663  }
2664 
2665  PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2666  DiagDirection dest_enterdir = enterdir;
2667  if (do_track_reservation) {
2668  res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2669  if (res_dest.tile == INVALID_TILE) {
2670  /* Reservation failed? */
2671  if (mark_stuck) MarkTrainAsStuck(v);
2672  if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2673  return FindFirstTrack(tracks);
2674  }
2675  if (res_dest.okay) {
2676  /* Got a valid reservation that ends at a safe target, quick exit. */
2677  if (got_reservation != nullptr) *got_reservation = true;
2678  if (changed_signal) MarkTileDirtyByTile(tile);
2680  return best_track;
2681  }
2682 
2683  /* Check if the train needs service here, so it has a chance to always find a depot.
2684  * Also check if the current order is a service order so we don't reserve a path to
2685  * the destination but instead to the next one if service isn't needed. */
2687  if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2688  }
2689 
2690  /* Save the current train order. The destructor will restore the old order on function exit. */
2691  VehicleOrderSaver orders(v);
2692 
2693  /* If the current tile is the destination of the current order and
2694  * a reservation was requested, advance to the next order.
2695  * Don't advance on a depot order as depots are always safe end points
2696  * for a path and no look-ahead is necessary. This also avoids a
2697  * problem with depot orders not part of the order list when the
2698  * order list itself is empty. */
2699  if (v->current_order.IsType(OT_LEAVESTATION)) {
2700  orders.SwitchToNextOrder(false);
2701  } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2702  v->current_order.IsType(OT_GOTO_STATION) ?
2704  v->tile == v->dest_tile))) {
2705  orders.SwitchToNextOrder(true);
2706  }
2707 
2708  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2709  /* Pathfinders are able to tell that route was only 'guessed'. */
2710  bool path_found = true;
2711  TileIndex new_tile = res_dest.tile;
2712 
2713  Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2714  if (new_tile == tile) best_track = next_track;
2715  v->HandlePathfindingResult(path_found);
2716  }
2717 
2718  /* No track reservation requested -> finished. */
2719  if (!do_track_reservation) return best_track;
2720 
2721  /* A path was found, but could not be reserved. */
2722  if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2723  if (mark_stuck) MarkTrainAsStuck(v);
2725  return best_track;
2726  }
2727 
2728  /* No possible reservation target found, we are probably lost. */
2729  if (res_dest.tile == INVALID_TILE) {
2730  /* Try to find any safe destination. */
2731  PBSTileInfo origin = FollowTrainReservation(v);
2732  if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2733  TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2734  best_track = FindFirstTrack(res);
2736  if (got_reservation != nullptr) *got_reservation = true;
2737  if (changed_signal) MarkTileDirtyByTile(tile);
2738  } else {
2740  if (mark_stuck) MarkTrainAsStuck(v);
2741  }
2742  return best_track;
2743  }
2744 
2745  if (got_reservation != nullptr) *got_reservation = true;
2746 
2747  /* Reservation target found and free, check if it is safe. */
2748  while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2749  /* Extend reservation until we have found a safe position. */
2750  DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2751  TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2753  if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2754  reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2755  }
2756 
2757  /* Get next order with destination. */
2758  if (orders.SwitchToNextOrder(true)) {
2759  PBSTileInfo cur_dest;
2760  bool path_found;
2761  DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2762  if (cur_dest.tile != INVALID_TILE) {
2763  res_dest = cur_dest;
2764  if (res_dest.okay) continue;
2765  /* Path found, but could not be reserved. */
2767  if (mark_stuck) MarkTrainAsStuck(v);
2768  if (got_reservation != nullptr) *got_reservation = false;
2769  changed_signal = false;
2770  break;
2771  }
2772  }
2773  /* No order or no safe position found, try any position. */
2774  if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2776  if (mark_stuck) MarkTrainAsStuck(v);
2777  if (got_reservation != nullptr) *got_reservation = false;
2778  changed_signal = false;
2779  }
2780  break;
2781  }
2782 
2784 
2785  if (changed_signal) MarkTileDirtyByTile(tile);
2786 
2787  orders.Restore();
2788  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
2790  final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2791  v->current_order.SetDestination(GetDepotIndex(final_dest));
2792  v->dest_tile = final_dest;
2794  }
2795 
2796  return best_track;
2797 }
2798 
2807 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2808 {
2809  assert(v->IsFrontEngine());
2810 
2811  /* We have to handle depots specially as the track follower won't look
2812  * at the depot tile itself but starts from the next tile. If we are still
2813  * inside the depot, a depot reservation can never be ours. */
2814  if (v->track == TRACK_BIT_DEPOT) {
2815  if (HasDepotReservation(v->tile)) {
2816  if (mark_as_stuck) MarkTrainAsStuck(v);
2817  return false;
2818  } else {
2819  /* Depot not reserved, but the next tile might be. */
2821  if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2822  }
2823  }
2824 
2825  Vehicle *other_train = nullptr;
2826  PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2827  /* The path we are driving on is already blocked by some other train.
2828  * This can only happen in certain situations when mixing path and
2829  * block signals or when changing tracks and/or signals.
2830  * Exit here as doing any further reservations will probably just
2831  * make matters worse. */
2832  if (other_train != nullptr && other_train->index != v->index) {
2833  if (mark_as_stuck) MarkTrainAsStuck(v);
2834  return false;
2835  }
2836  /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2837  if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2838  /* Can't be stuck then. */
2840  ClrBit(v->flags, VRF_TRAIN_STUCK);
2841  return true;
2842  }
2843 
2844  /* If we are in a depot, tentatively reserve the depot. */
2845  if (v->track == TRACK_BIT_DEPOT) {
2846  SetDepotReservation(v->tile, true);
2848  }
2849 
2850  DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2851  TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2853 
2855 
2856  bool res_made = false;
2857  ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2858 
2859  if (!res_made) {
2860  /* Free the depot reservation as well. */
2861  if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2862  return false;
2863  }
2864 
2865  if (HasBit(v->flags, VRF_TRAIN_STUCK)) {
2866  v->wait_counter = 0;
2868  }
2869  ClrBit(v->flags, VRF_TRAIN_STUCK);
2870  return true;
2871 }
2872 
2873 
2874 static bool CheckReverseTrain(const Train *v)
2875 {
2877  v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2878  !(v->direction & 1)) {
2879  return false;
2880  }
2881 
2882  assert(v->track != TRACK_BIT_NONE);
2883 
2885  case VPF_NPF: return NPFTrainCheckReverse(v);
2886  case VPF_YAPF: return YapfTrainCheckReverse(v);
2887 
2888  default: NOT_REACHED();
2889  }
2890 }
2891 
2898 {
2899  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
2900 
2901  const Station *st = Station::Get(station);
2902  if (!(st->facilities & FACIL_TRAIN)) {
2903  /* The destination station has no trainstation tiles. */
2904  this->IncrementRealOrderIndex();
2905  return 0;
2906  }
2907 
2908  return st->xy;
2909 }
2910 
2913 {
2914  Train *v = this;
2915  do {
2916  v->colourmap = PAL_NONE;
2917  v->UpdateViewport(true, false);
2918  } while ((v = v->Next()) != nullptr);
2919 
2920  /* need to update acceleration and cached values since the goods on the train changed. */
2921  this->CargoChanged();
2922  this->UpdateAcceleration();
2923 }
2924 
2933 {
2935  default: NOT_REACHED();
2936  case AM_ORIGINAL:
2937  return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
2938 
2939  case AM_REALISTIC:
2940  return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
2941  }
2942 }
2943 
2949 static void TrainEnterStation(Train *v, StationID station)
2950 {
2951  v->last_station_visited = station;
2952 
2953  /* check if a train ever visited this station before */
2954  Station *st = Station::Get(station);
2955  if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
2956  st->had_vehicle_of_type |= HVOT_TRAIN;
2957  SetDParam(0, st->index);
2959  STR_NEWS_FIRST_TRAIN_ARRIVAL,
2961  v->index,
2962  st->index
2963  );
2964  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
2965  Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
2966  }
2967 
2968  v->force_proceed = TFP_NONE;
2970 
2971  v->BeginLoading();
2972 
2974  TriggerStationAnimation(st, v->tile, SAT_TRAIN_ARRIVES);
2975 }
2976 
2977 /* Check if the vehicle is compatible with the specified tile */
2978 static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
2979 {
2980  return IsTileOwner(tile, v->owner) &&
2981  (!v->IsFrontEngine() || HasBit(v->compatible_railtypes, GetRailType(tile)));
2982 }
2983 
2986  byte small_turn;
2987  byte large_turn;
2988  byte z_up;
2989  byte z_down;
2990 };
2991 
2994  /* normal accel */
2995  {256 / 4, 256 / 2, 256 / 4, 2},
2996  {256 / 4, 256 / 2, 256 / 4, 2},
2997  {0, 256 / 2, 256 / 4, 2},
2998 };
2999 
3005 static inline void AffectSpeedByZChange(Train *v, int old_z)
3006 {
3007  if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3008 
3010 
3011  if (old_z < v->z_pos) {
3012  v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3013  } else {
3014  uint16 spd = v->cur_speed + asp->z_down;
3015  if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3016  }
3017 }
3018 
3019 static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
3020 {
3021  if (IsTileType(tile, MP_RAILWAY) &&
3024  Trackdir trackdir = FindFirstTrackdir(tracks);
3025  if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3026  /* A PBS block with a non-PBS signal facing us? */
3027  if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
3028  }
3029  }
3030  return false;
3031 }
3032 
3035 {
3036  for (const Train *u = this; u != nullptr; u = u->Next()) {
3037  switch (u->track) {
3038  case TRACK_BIT_WORMHOLE:
3040  break;
3041  case TRACK_BIT_DEPOT:
3042  break;
3043  default:
3044  TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3045  break;
3046  }
3047  }
3048 }
3049 
3056 uint Train::Crash(bool flooded)
3057 {
3058  uint pass = 0;
3059  if (this->IsFrontEngine()) {
3060  pass += 2; // driver
3061 
3062  /* Remove the reserved path in front of the train if it is not stuck.
3063  * Also clear all reserved tracks the train is currently on. */
3064  if (!HasBit(this->flags, VRF_TRAIN_STUCK)) FreeTrainTrackReservation(this);
3065  for (const Train *v = this; v != nullptr; v = v->Next()) {
3067  if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3068  /* ClearPathReservation will not free the wormhole exit
3069  * if the train has just entered the wormhole. */
3071  }
3072  }
3073 
3074  /* we may need to update crossing we were approaching,
3075  * but must be updated after the train has been marked crashed */
3076  TileIndex crossing = TrainApproachingCrossingTile(this);
3077  if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3078 
3079  /* Remove the loading indicators (if any) */
3081  }
3082 
3083  pass += this->GroundVehicleBase::Crash(flooded);
3084 
3085  this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3086  return pass;
3087 }
3088 
3095 static uint TrainCrashed(Train *v)
3096 {
3097  uint num = 0;
3098 
3099  /* do not crash train twice */
3100  if (!(v->vehstatus & VS_CRASHED)) {
3101  num = v->Crash();
3102  AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3103  Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN));
3104  }
3105 
3106  /* Try to re-reserve track under already crashed train too.
3107  * Crash() clears the reservation! */
3109 
3110  return num;
3111 }
3112 
3116  uint num;
3117 };
3118 
3125 static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
3126 {
3128 
3129  /* not a train or in depot */
3130  if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return nullptr;
3131 
3132  /* do not crash into trains of another company. */
3133  if (v->owner != tcc->v->owner) return nullptr;
3134 
3135  /* get first vehicle now to make most usual checks faster */
3136  Train *coll = Train::From(v)->First();
3137 
3138  /* can't collide with own wagons */
3139  if (coll == tcc->v) return nullptr;
3140 
3141  int x_diff = v->x_pos - tcc->v->x_pos;
3142  int y_diff = v->y_pos - tcc->v->y_pos;
3143 
3144  /* Do fast calculation to check whether trains are not in close vicinity
3145  * and quickly reject trains distant enough for any collision.
3146  * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3147  * Differences are then ORed and then we check for any higher bits */
3148  uint hash = (y_diff + 7) | (x_diff + 7);
3149  if (hash & ~15) return nullptr;
3150 
3151  /* Slower check using multiplication */
3152  int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (tcc->v->gcache.cached_veh_length + 1) / 2 - 1;
3153  if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return nullptr;
3154 
3155  /* Happens when there is a train under bridge next to bridge head */
3156  if (abs(v->z_pos - tcc->v->z_pos) > 5) return nullptr;
3157 
3158  /* crash both trains */
3159  tcc->num += TrainCrashed(tcc->v);
3160  tcc->num += TrainCrashed(coll);
3161 
3162  return nullptr; // continue searching
3163 }
3164 
3173 {
3174  /* can't collide in depot */
3175  if (v->track == TRACK_BIT_DEPOT) return false;
3176 
3177  assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3178 
3179  TrainCollideChecker tcc;
3180  tcc.v = v;
3181  tcc.num = 0;
3182 
3183  /* find colliding vehicles */
3184  if (v->track == TRACK_BIT_WORMHOLE) {
3187  } else {
3189  }
3190 
3191  /* any dead -> no crash */
3192  if (tcc.num == 0) return false;
3193 
3194  SetDParam(0, tcc.num);
3195  AddTileNewsItem(STR_NEWS_TRAIN_CRASH, NT_ACCIDENT, v->tile);
3196 
3197  ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3198  if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3199  return true;
3200 }
3201 
3202 static Vehicle *CheckTrainAtSignal(Vehicle *v, void *data)
3203 {
3204  if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return nullptr;
3205 
3206  Train *t = Train::From(v);
3207  DiagDirection exitdir = *(DiagDirection *)data;
3208 
3209  /* not front engine of a train, inside wormhole or depot, crashed */
3210  if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return nullptr;
3211 
3212  if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return nullptr;
3213 
3214  return t;
3215 }
3216 
3224 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3225 {
3226  Train *first = v->First();
3227  Train *prev;
3228  bool direction_changed = false; // has direction of any part changed?
3229 
3230  /* For every vehicle after and including the given vehicle */
3231  for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3232  DiagDirection enterdir = DIAGDIR_BEGIN;
3233  bool update_signals_crossing = false; // will we update signals or crossing state?
3234 
3236  if (v->track != TRACK_BIT_WORMHOLE) {
3237  /* Not inside tunnel */
3238  if (gp.old_tile == gp.new_tile) {
3239  /* Staying in the old tile */
3240  if (v->track == TRACK_BIT_DEPOT) {
3241  /* Inside depot */
3242  gp.x = v->x_pos;
3243  gp.y = v->y_pos;
3244  } else {
3245  /* Not inside depot */
3246 
3247  /* Reverse when we are at the end of the track already, do not move to the new position */
3248  if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3249 
3250  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3251  if (HasBit(r, VETS_CANNOT_ENTER)) {
3252  goto invalid_rail;
3253  }
3254  if (HasBit(r, VETS_ENTERED_STATION)) {
3255  /* The new position is the end of the platform */
3257  }
3258  }
3259  } else {
3260  /* A new tile is about to be entered. */
3261 
3262  /* Determine what direction we're entering the new tile from */
3263  enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3264  assert(IsValidDiagDirection(enterdir));
3265 
3266  /* Get the status of the tracks in the new tile and mask
3267  * away the bits that aren't reachable. */
3268  TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3269  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3270 
3271  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3272  TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3273 
3274  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3275  if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3276  /* We allow wagons to make 90 deg turns, because forbid_90_deg
3277  * can be switched on halfway a turn */
3278  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3279  }
3280 
3281  if (bits == TRACK_BIT_NONE) goto invalid_rail;
3282 
3283  /* Check if the new tile constrains tracks that are compatible
3284  * with the current train, if not, bail out. */
3285  if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3286 
3287  TrackBits chosen_track;
3288  if (prev == nullptr) {
3289  /* Currently the locomotive is active. Determine which one of the
3290  * available tracks to choose */
3291  chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3292  assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3293 
3294  if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3295  /* For each signal we find decrease the counter by one.
3296  * We start at two, so the first signal we pass decreases
3297  * this to one, then if we reach the next signal it is
3298  * decreased to zero and we won't pass that new signal. */
3299  Trackdir dir = FindFirstTrackdir(trackdirbits);
3300  if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3302  GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3303  /* However, we do not want to be stopped by PBS signals
3304  * entered via the back. */
3305  v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3307  }
3308  }
3309 
3310  /* Check if it's a red signal and that force proceed is not clicked. */
3311  if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3312  /* In front of a red signal */
3313  Trackdir i = FindFirstTrackdir(trackdirbits);
3314 
3315  /* Don't handle stuck trains here. */
3316  if (HasBit(v->flags, VRF_TRAIN_STUCK)) return false;
3317 
3319  v->cur_speed = 0;
3320  v->subspeed = 0;
3321  v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3323  } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3324  v->cur_speed = 0;
3325  v->subspeed = 0;
3326  v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3328  DiagDirection exitdir = TrackdirToExitdir(i);
3329  TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3330 
3331  exitdir = ReverseDiagDir(exitdir);
3332 
3333  /* check if a train is waiting on the other side */
3334  if (!HasVehicleOnPos(o_tile, &exitdir, &CheckTrainAtSignal)) return false;
3335  }
3336  }
3337 
3338  /* If we would reverse but are currently in a PBS block and
3339  * reversing of stuck trains is disabled, don't reverse.
3340  * This does not apply if the reason for reversing is a one-way
3341  * signal blocking us, because a train would then be stuck forever. */
3343  UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3344  v->wait_counter = 0;
3345  return false;
3346  }
3347  goto reverse_train_direction;
3348  } else {
3349  TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3350  }
3351  } else {
3352  /* The wagon is active, simply follow the prev vehicle. */
3353  if (prev->tile == gp.new_tile) {
3354  /* Choose the same track as prev */
3355  if (prev->track == TRACK_BIT_WORMHOLE) {
3356  /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3357  * However, just choose the track into the wormhole. */
3358  assert(IsTunnel(prev->tile));
3359  chosen_track = bits;
3360  } else {
3361  chosen_track = prev->track;
3362  }
3363  } else {
3364  /* Choose the track that leads to the tile where prev is.
3365  * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3366  * I.e. when the tile between them has only space for a single vehicle like
3367  * 1) horizontal/vertical track tiles and
3368  * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3369  * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3370  */
3371  static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3376  };
3377  DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3378  assert(IsValidDiagDirection(exitdir));
3379  chosen_track = _connecting_track[enterdir][exitdir];
3380  }
3381  chosen_track &= bits;
3382  }
3383 
3384  /* Make sure chosen track is a valid track */
3385  assert(
3386  chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3387  chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3388  chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3389 
3390  /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3391  const byte *b = _initial_tile_subcoord[FIND_FIRST_BIT(chosen_track)][enterdir];
3392  gp.x = (gp.x & ~0xF) | b[0];
3393  gp.y = (gp.y & ~0xF) | b[1];
3394  Direction chosen_dir = (Direction)b[2];
3395 
3396  /* Call the landscape function and tell it that the vehicle entered the tile */
3397  uint32 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3398  if (HasBit(r, VETS_CANNOT_ENTER)) {
3399  goto invalid_rail;
3400  }
3401 
3402  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
3403  Track track = FindFirstTrack(chosen_track);
3404  Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3405  if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3408  }
3409 
3410  /* Clear any track reservation when the last vehicle leaves the tile */
3411  if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3412 
3413  v->tile = gp.new_tile;
3414 
3417  }
3418 
3419  v->track = chosen_track;
3420  assert(v->track);
3421  }
3422 
3423  /* We need to update signal status, but after the vehicle position hash
3424  * has been updated by UpdateInclination() */
3425  update_signals_crossing = true;
3426 
3427  if (chosen_dir != v->direction) {
3428  if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3430  DirDiff diff = DirDifference(v->direction, chosen_dir);
3431  v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3432  }
3433  direction_changed = true;
3434  v->direction = chosen_dir;
3435  }
3436 
3437  if (v->IsFrontEngine()) {
3438  v->wait_counter = 0;
3439 
3440  /* If we are approaching a crossing that is reserved, play the sound now. */
3442  if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3443 
3444  /* Always try to extend the reservation when entering a tile. */
3445  CheckNextTrainTile(v);
3446  }
3447 
3448  if (HasBit(r, VETS_ENTERED_STATION)) {
3449  /* The new position is the location where we want to stop */
3451  }
3452  }
3453  } else {
3455  /* Perform look-ahead on tunnel exit. */
3456  if (v->IsFrontEngine()) {
3458  CheckNextTrainTile(v);
3459  }
3460  /* Prevent v->UpdateInclination() being called with wrong parameters.
3461  * This could happen if the train was reversed inside the tunnel/bridge. */
3462  if (gp.old_tile == gp.new_tile) {
3464  }
3465  } else {
3466  v->x_pos = gp.x;
3467  v->y_pos = gp.y;
3468  v->UpdatePosition();
3469  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
3470  continue;
3471  }
3472  }
3473 
3474  /* update image of train, as well as delta XY */
3475  v->UpdateDeltaXY();
3476 
3477  v->x_pos = gp.x;
3478  v->y_pos = gp.y;
3479  v->UpdatePosition();
3480 
3481  /* update the Z position of the vehicle */
3482  int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3483 
3484  if (prev == nullptr) {
3485  /* This is the first vehicle in the train */
3486  AffectSpeedByZChange(v, old_z);
3487  }
3488 
3489  if (update_signals_crossing) {
3490  if (v->IsFrontEngine()) {
3491  if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3492  /* We are entering a block with PBS signals right now, but
3493  * not through a PBS signal. This means we don't have a
3494  * reservation right now. As a conventional signal will only
3495  * ever be green if no other train is in the block, getting
3496  * a path should always be possible. If the player built
3497  * such a strange network that it is not possible, the train
3498  * will be marked as stuck and the player has to deal with
3499  * the problem. */
3500  if ((!HasReservedTracks(gp.new_tile, v->track) &&
3501  !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3502  !TryPathReserve(v)) {
3503  MarkTrainAsStuck(v);
3504  }
3505  }
3506  }
3507 
3508  /* Signals can only change when the first
3509  * (above) or the last vehicle moves. */
3510  if (v->Next() == nullptr) {
3511  TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3513  }
3514  }
3515 
3516  /* Do not check on every tick to save some computing time. */
3518  }
3519 
3520  if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3521 
3522  return true;
3523 
3524 invalid_rail:
3525  /* We've reached end of line?? */
3526  if (prev != nullptr) error("Disconnecting train");
3527 
3528 reverse_train_direction:
3529  if (reverse) {
3530  v->wait_counter = 0;
3531  v->cur_speed = 0;
3532  v->subspeed = 0;
3534  }
3535 
3536  return false;
3537 }
3538 
3546 {
3547  TrackBits *trackbits = (TrackBits *)data;
3548 
3549  if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
3550  TrackBits train_tbits = Train::From(v)->track;
3551  if (train_tbits == TRACK_BIT_WORMHOLE) {
3552  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3554  } else if (train_tbits != TRACK_BIT_DEPOT) {
3555  *trackbits |= train_tbits;
3556  }
3557  }
3558 
3559  return nullptr;
3560 }
3561 
3569 static void DeleteLastWagon(Train *v)
3570 {
3571  Train *first = v->First();
3572 
3573  /* Go to the last wagon and delete the link pointing there
3574  * *u is then the one-before-last wagon, and *v the last
3575  * one which will physically be removed */
3576  Train *u = v;
3577  for (; v->Next() != nullptr; v = v->Next()) u = v;
3578  u->SetNext(nullptr);
3579 
3580  if (first != v) {
3581  /* Recalculate cached train properties */
3582  first->ConsistChanged(CCF_ARRANGE);
3583  /* Update the depot window if the first vehicle is in depot -
3584  * if v == first, then it is updated in PreDestructor() */
3585  if (first->track == TRACK_BIT_DEPOT) {
3587  }
3588  v->last_station_visited = first->last_station_visited; // for PreDestructor
3589  }
3590 
3591  /* 'v' shouldn't be accessed after it has been deleted */
3592  TrackBits trackbits = v->track;
3593  TileIndex tile = v->tile;
3594  Owner owner = v->owner;
3595 
3596  delete v;
3597  v = nullptr; // make sure nobody will try to read 'v' anymore
3598 
3599  if (trackbits == TRACK_BIT_WORMHOLE) {
3600  /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3602  }
3603 
3604  Track track = TrackBitsToTrack(trackbits);
3605  if (HasReservedTracks(tile, trackbits)) {
3606  UnreserveRailTrack(tile, track);
3607 
3608  /* If there are still crashed vehicles on the tile, give the track reservation to them */
3609  TrackBits remaining_trackbits = TRACK_BIT_NONE;
3610  FindVehicleOnPos(tile, &remaining_trackbits, CollectTrackbitsFromCrashedVehiclesEnum);
3611 
3612  /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3613  assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3614  for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3615  }
3616 
3617  /* check if the wagon was on a road/rail-crossing */
3618  if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3619 
3620  /* Update signals */
3621  if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3623  } else {
3624  SetSignalsOnBothDir(tile, track, owner);
3625  }
3626 }
3627 
3633 {
3634  static const DirDiff delta[] = {
3636  };
3637 
3638  do {
3639  /* We don't need to twist around vehicles if they're not visible */
3640  if (!(v->vehstatus & VS_HIDDEN)) {
3641  v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3642  /* Refrain from updating the z position of the vehicle when on
3643  * a bridge, because UpdateInclination() will put the vehicle under
3644  * the bridge in that case */
3645  if (v->track != TRACK_BIT_WORMHOLE) {
3646  v->UpdatePosition();
3647  v->UpdateInclination(false, true);
3648  } else {
3649  v->UpdateViewport(false, true);
3650  }
3651  }
3652  } while ((v = v->Next()) != nullptr);
3653 }
3654 
3660 static bool HandleCrashedTrain(Train *v)
3661 {
3662  int state = ++v->crash_anim_pos;
3663 
3664  if (state == 4 && !(v->vehstatus & VS_HIDDEN)) {
3666  }
3667 
3668  uint32 r;
3669  if (state <= 200 && Chance16R(1, 7, r)) {
3670  int index = (r * 10 >> 16);
3671 
3672  Vehicle *u = v;
3673  do {
3674  if (--index < 0) {
3675  r = Random();
3676 
3678  GB(r, 8, 3) + 2,
3679  GB(r, 16, 3) + 2,
3680  GB(r, 0, 3) + 5,
3682  break;
3683  }
3684  } while ((u = u->Next()) != nullptr);
3685  }
3686 
3687  if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3688 
3689  if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3690  bool ret = v->Next() != nullptr;
3691  DeleteLastWagon(v);
3692  return ret;
3693  }
3694 
3695  return true;
3696 }
3697 
3699 static const uint16 _breakdown_speeds[16] = {
3700  225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3701 };
3702 
3703 
3712 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3713 {
3714  /* Calc position within the current tile */
3715  uint x = v->x_pos & 0xF;
3716  uint y = v->y_pos & 0xF;
3717 
3718  /* for diagonal directions, 'x' will be 0..15 -
3719  * for other directions, it will be 1, 3, 5, ..., 15 */
3720  switch (v->direction) {
3721  case DIR_N : x = ~x + ~y + 25; break;
3722  case DIR_NW: x = y; FALLTHROUGH;
3723  case DIR_NE: x = ~x + 16; break;
3724  case DIR_E : x = ~x + y + 9; break;
3725  case DIR_SE: x = y; break;
3726  case DIR_S : x = x + y - 7; break;
3727  case DIR_W : x = ~y + x + 9; break;
3728  default: break;
3729  }
3730 
3731  /* Do not reverse when approaching red signal. Make sure the vehicle's front
3732  * does not cross the tile boundary when we do reverse, but as the vehicle's
3733  * location is based on their center, use half a vehicle's length as offset.
3734  * Multiply the half-length by two for straight directions to compensate that
3735  * we only get odd x offsets there. */
3736  if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3737  /* we are too near the tile end, reverse now */
3738  v->cur_speed = 0;
3739  if (reverse) ReverseTrainDirection(v);
3740  return false;
3741  }
3742 
3743  /* slow down */
3745  uint16 break_speed = _breakdown_speeds[x & 0xF];
3746  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3747 
3748  return true;
3749 }
3750 
3751 
3757 static bool TrainCanLeaveTile(const Train *v)
3758 {
3759  /* Exit if inside a tunnel/bridge or a depot */
3760  if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3761 
3762  TileIndex tile = v->tile;
3763 
3764  /* entering a tunnel/bridge? */
3765  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3767  if (DiagDirToDir(dir) == v->direction) return false;
3768  }
3769 
3770  /* entering a depot? */
3771  if (IsRailDepotTile(tile)) {
3773  if (DiagDirToDir(dir) == v->direction) return false;
3774  }
3775 
3776  return true;
3777 }
3778 
3779 
3788 {
3789  assert(v->IsFrontEngine());
3790  assert(!(v->vehstatus & VS_CRASHED));
3791 
3792  if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3793 
3794  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3795  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3796 
3797  /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3798  if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3799  !CheckCompatibleRail(v, tile)) {
3800  return INVALID_TILE;
3801  }
3802 
3803  return tile;
3804 }
3805 
3806 
3814 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3815 {
3816  /* First, handle broken down train */
3817 
3818  int t = v->breakdown_ctr;
3819  if (t > 1) {
3821 
3822  uint16 break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3823  if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3824  } else {
3825  v->vehstatus &= ~VS_TRAIN_SLOWING;
3826  }
3827 
3828  if (!TrainCanLeaveTile(v)) return true;
3829 
3830  /* Determine the non-diagonal direction in which we will exit this tile */
3831  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3832  /* Calculate next tile */
3833  TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3834 
3835  /* Determine the track status on the next tile */
3836  TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3837  TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3838 
3839  TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3840  TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3841 
3842  /* We are sure the train is not entering a depot, it is detected above */
3843 
3844  /* mask unreachable track bits if we are forbidden to do 90deg turns */
3845  TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3847  bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3848  }
3849 
3850  /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3851  if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3852  return TrainApproachingLineEnd(v, false, reverse);
3853  }
3854 
3855  /* approaching red signal */
3856  if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3857 
3858  /* approaching a rail/road crossing? then make it red */
3860 
3861  return true;
3862 }
3863 
3864 
3865 static bool TrainLocoHandler(Train *v, bool mode)
3866 {
3867  /* train has crashed? */
3868  if (v->vehstatus & VS_CRASHED) {
3869  return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3870  }
3871 
3872  if (v->force_proceed != TFP_NONE) {
3873  ClrBit(v->flags, VRF_TRAIN_STUCK);
3875  }
3876 
3877  /* train is broken down? */
3878  if (v->HandleBreakdown()) return true;
3879 
3880  if (HasBit(v->flags, VRF_REVERSING) && v->cur_speed == 0) {
3882  }
3883 
3884  /* exit if train is stopped */
3885  if ((v->vehstatus & VS_STOPPED) && v->cur_speed == 0) return true;
3886 
3887  bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3888  if (ProcessOrders(v) && CheckReverseTrain(v)) {
3889  v->wait_counter = 0;
3890  v->cur_speed = 0;
3891  v->subspeed = 0;
3892  ClrBit(v->flags, VRF_LEAVING_STATION);
3894  return true;
3895  } else if (HasBit(v->flags, VRF_LEAVING_STATION)) {
3896  /* Try to reserve a path when leaving the station as we
3897  * might not be marked as wanting a reservation, e.g.
3898  * when an overlength train gets turned around in a station. */
3899  DiagDirection dir = VehicleExitDir(v->direction, v->track);
3901 
3903  TryPathReserve(v, true, true);
3904  }
3905  ClrBit(v->flags, VRF_LEAVING_STATION);
3906  }
3907 
3908  v->HandleLoading(mode);
3909 
3910  if (v->current_order.IsType(OT_LOADING)) return true;
3911 
3912  if (CheckTrainStayInDepot(v)) return true;
3913 
3914  if (!mode) v->ShowVisualEffect();
3915 
3916  /* We had no order but have an order now, do look ahead. */
3917  if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
3918  CheckNextTrainTile(v);
3919  }
3920 
3921  /* Handle stuck trains. */
3922  if (!mode && HasBit(v->flags, VRF_TRAIN_STUCK)) {
3923  ++v->wait_counter;
3924 
3925  /* Should we try reversing this tick if still stuck? */
3927 
3928  if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
3929  if (!TryPathReserve(v)) {
3930  /* Still stuck. */
3931  if (turn_around) ReverseTrainDirection(v);
3932 
3934  /* Show message to player. */
3936  SetDParam(0, v->index);
3937  AddVehicleAdviceNewsItem(STR_NEWS_TRAIN_IS_STUCK, v->index);
3938  }
3939  v->wait_counter = 0;
3940  }
3941  /* Exit if force proceed not pressed, else reset stuck flag anyway. */
3942  if (v->force_proceed == TFP_NONE) return true;
3943  ClrBit(v->flags, VRF_TRAIN_STUCK);
3944  v->wait_counter = 0;
3946  }
3947  }
3948 
3949  if (v->current_order.IsType(OT_LEAVESTATION)) {
3950  v->current_order.Free();
3952  return true;
3953  }
3954 
3955  int j = v->UpdateSpeed();
3956 
3957  /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
3958  if (v->cur_speed == 0 && (v->vehstatus & VS_STOPPED)) {
3959  /* If we manually stopped, we're not force-proceeding anymore. */
3960  v->force_proceed = TFP_NONE;
3962  }
3963 
3964  int adv_spd = v->GetAdvanceDistance();
3965  if (j < adv_spd) {
3966  /* if the vehicle has speed 0, update the last_speed field. */
3967  if (v->cur_speed == 0) v->SetLastSpeed();
3968  } else {
3970  /* Loop until the train has finished moving. */
3971  for (;;) {
3972  j -= adv_spd;
3973  TrainController(v, nullptr);
3974  /* Don't continue to move if the train crashed. */
3975  if (CheckTrainCollision(v)) break;
3976  /* Determine distance to next map position */
3977  adv_spd = v->GetAdvanceDistance();
3978 
3979  /* No more moving this tick */
3980  if (j < adv_spd || v->cur_speed == 0) break;
3981 
3982  OrderType order_type = v->current_order.GetType();
3983  /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
3984  if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
3986  IsTileType(v->tile, MP_STATION) &&
3988  ProcessOrders(v);
3989  }
3990  }
3991  v->SetLastSpeed();
3992  }
3993 
3994  for (Train *u = v; u != nullptr; u = u->Next()) {
3995  if ((u->vehstatus & VS_HIDDEN) != 0) continue;
3996 
3997  u->UpdateViewport(false, false);
3998  }
3999 
4000  if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4001 
4002  return true;
4003 }
4004 
4010 {
4011  Money cost = 0;
4012  const Train *v = this;
4013 
4014  do {
4015  const Engine *e = v->GetEngine();
4016  if (e->u.rail.running_cost_class == INVALID_PRICE) continue;
4017 
4018  uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->u.rail.running_cost);
4019  if (cost_factor == 0) continue;
4020 
4021  /* Halve running cost for multiheaded parts */
4022  if (v->IsMultiheaded()) cost_factor /= 2;
4023 
4024  cost += GetPrice(e->u.rail.running_cost_class, cost_factor, e->GetGRF());
4025  } while ((v = v->GetNextVehicle()) != nullptr);
4026 
4027  return cost;
4028 }
4029 
4035 {
4036  this->tick_counter++;
4037 
4038  if (this->IsFrontEngine()) {
4040 
4041  if (!(this->vehstatus & VS_STOPPED) || this->cur_speed > 0) this->running_ticks++;
4042 
4043  this->current_order_time++;
4044 
4045  if (!TrainLocoHandler(this, false)) return false;
4046 
4047  return TrainLocoHandler(this, true);
4048  } else if (this->IsFreeWagon() && (this->vehstatus & VS_CRASHED)) {
4049  /* Delete flooded standalone wagon chain */
4050  if (++this->crash_anim_pos >= 4400) {
4051  delete this;
4052  return false;
4053  }
4054  }
4055 
4056  return true;
4057 }
4058 
4064 {
4065  if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4066  if (v->IsChainInDepot()) {
4068  return;
4069  }
4070 
4071  uint max_penalty;
4073  case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
4074  case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
4075  default: NOT_REACHED();
4076  }
4077 
4078  FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4079  /* Only go to the depot if it is not too far out of our way. */
4080  if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4081  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4082  /* If we were already heading for a depot but it has
4083  * suddenly moved farther away, we continue our normal
4084  * schedule? */
4085  v->current_order.MakeDummy();
4087  }
4088  return;
4089  }
4090 
4091  DepotID depot = GetDepotIndex(tfdd.tile);
4092 
4093  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4094  v->current_order.GetDestination() != depot &&
4095  !Chance16(3, 16)) {
4096  return;
4097  }
4098 
4101  v->dest_tile = tfdd.tile;
4103 }
4104 
4107 {
4108  AgeVehicle(this);
4109 
4110  if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4111 
4112  if (this->IsFrontEngine()) {
4113  CheckVehicleBreakdown(this);
4114 
4116 
4117  CheckOrders(this);
4118 
4119  /* update destination */
4120  if (this->current_order.IsType(OT_GOTO_STATION)) {
4122  if (tile != INVALID_TILE) this->dest_tile = tile;
4123  }
4124 
4125  if (this->running_ticks != 0) {
4126  /* running costs */
4128 
4129  this->profit_this_year -= cost.GetCost();
4130  this->running_ticks = 0;
4131 
4132  SubtractMoneyFromCompanyFract(this->owner, cost);
4133 
4136  }
4137  }
4138 }
4139 
4145 {
4146  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
4147 
4148  if (this->track == TRACK_BIT_DEPOT) {
4149  /* We'll assume the train is facing outwards */
4150  return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4151  }
4152 
4153  if (this->track == TRACK_BIT_WORMHOLE) {
4154  /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4155  return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4156  }
4157 
4158  return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4159 }
4160 
4161 uint16 Train::GetMaxWeight() const
4162 {
4163  uint16 weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->GetEngine()->DetermineCapacity(this));
4164 
4165  /* Vehicle weight is not added for articulated parts. */
4166  if (!this->IsArticulatedPart()) {
4167  weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
4168  }
4169 
4170  /* Powered wagons have extra weight added. */
4171  if (HasBit(this->flags, VRF_POWEREDWAGON)) {
4172  weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
4173  }
4174 
4175  return weight;
4176 }
Train::GetDisplayImageWidth
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
Definition: train_cmd.cpp:457
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:2540
GUISettings::lost_vehicle_warn
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
Definition: settings_type.h:109
SpecializedVehicle::GetNextVehicle
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Definition: vehicle_base.h:1142
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
VehicleExitDir
static DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Definition: track_func.h:713
Train::IsPrimaryVehicle
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
Definition: train.h:116
SetTrainGroupID
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
Definition: group_cmd.cpp:721
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:166
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:730
FindFirstTrackdir
static Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
Definition: track_func.h:210
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:203
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:1251
Engine::GetGRFID
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:153
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:352
PathfinderSettings::npf
NPFSettings npf
pathfinder settings for the new pathfinder
Definition: settings_type.h:472
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:3252
Order::MakeDummy
void MakeDummy()
Makes this order a Dummy order.
Definition: order_cmd.cpp:133
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:469
Train::GetMaxWeight
uint16 GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
Definition: train_cmd.cpp:4161
UpdateLevelCrossing
void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
Definition: train_cmd.cpp:1757
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:1115
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:962
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:71
Rect::Height
int Height() const
Get height of Rect.
Definition: geometry_type.hpp:85
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
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:284
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3154
MutableSpriteCache::sprite_seq
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Definition: vehicle_base.h:197
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:264
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:961
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:256
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:628
VehicleSettings::train_acceleration_model
uint8 train_acceleration_model
realistic acceleration for trains
Definition: settings_type.h:489
Vehicle::x_pos
int32 x_pos
x coordinate.
Definition: vehicle_base.h:283
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
CmdBuildRailWagon
static CommandCost CmdBuildRailWagon(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
Definition: train_cmd.cpp:613
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:155
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:462
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:28
MaybeBarCrossingWithSound
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
Definition: train_cmd.cpp:1805
TrainCache::cached_tilt
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition: train.h:76
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:2986
Train::GetRunningCost
Money GetRunningCost() const override
Get running cost for the train consist.
Definition: train_cmd.cpp:4009
HasVehicleOnPos
bool HasVehicleOnPos(TileIndex tile, void *data, VehicleFromPosProc *proc)
Checks whether a vehicle is on a specific location.
Definition: vehicle.cpp:513
Train::GetCurrentMaxSpeed
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
Definition: train_cmd.cpp:379
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:1689
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:41
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:2261
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:2105
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:610
_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:1098
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:276
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:296
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition: direction_type.h:125
Station
Station data structure.
Definition: station_base.h:454
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:104
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:285
TrainCache::cached_curve_speed_mod
int cached_curve_speed_mod
curve speed modifier of the entire train
Definition: train.h:77
ProcessConditionalOrder
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
Definition: order_cmd.cpp:1932
UpdateStatusAfterSwap
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
Definition: train_cmd.cpp:1577
VehicleSpriteSeq::Set
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
Definition: vehicle_base.h:165
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:986
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:313
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:332
train_sprites.h
NormaliseTrainHead
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
Definition: train_cmd.cpp:1156
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:2587
VS_DEFPAL
@ VS_DEFPAL
Use default vehicle palette.
Definition: vehicle_base.h:37
DepotID
uint16 DepotID
Type for the unique identifier of depots.
Definition: depot_type.h:15
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:550
Pool::PoolItem<&_vehicle_pool >::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:235
Vehicle::SetNext
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition: vehicle.cpp:2741
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:118
Train::crash_anim_pos
uint16 crash_anim_pos
Crash animation counter.
Definition: train.h:94
Vehicle::acceleration
byte acceleration
used by train & aircraft
Definition: vehicle_base.h:309
MakeTrainBackup
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
Definition: train_cmd.cpp:845
AddArticulatedParts
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
Definition: articulated_vehicles.cpp:318
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:288
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:341
Order::Free
void Free()
'Free' the order
Definition: order_cmd.cpp:63
InsertInConsist
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
Definition: train_cmd.cpp:894
Train::UpdateSpeed
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
Definition: train_cmd.cpp:2932
Train::GetAccelerationStatus
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition: train.h:272
misc_cmd.h
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:586
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:132
INVALID_TILE
static constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:108
UnScaleGUI
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition: zoom_func.h:77
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:536
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:493
HideFillingPercent
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Definition: misc_gui.cpp:650
TileIndex
The index/ID of a Tile.
Definition: tile_type.h:85
TracksOverlap
static bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition: track_func.h:644
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
Vehicle::next
Vehicle * next
pointer to the next vehicle in the chain
Definition: vehicle_base.h:229
Vehicle::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition: vehicle.cpp:751
IsValidDiagDirection
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition: direction_func.h:21
SetCrossingReservation
static void SetCrossingReservation(TileIndex t, bool b)
Set the reservation state of the rail crossing.
Definition: road_map.h:393
RestoreTrainBackup
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
Definition: train_cmd.cpp:854
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:714
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
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:2301
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:330
GetTrackBits
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
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:636
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
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:53
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:1487
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:49
Engine::GetLifeLengthInDays
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition: engine.cpp:437
NPFTrainCheckReverse
bool NPFTrainCheckReverse(const Train *v)
Returns true if it is better to reverse the train before leaving station using NPF.
Definition: npf.cpp:1294
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:38
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:908
EngineImageType
EngineImageType
Visualisation contexts of vehicles and engines.
Definition: vehicle_type.h:86
Engine
Definition: engine_base.h:36
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:261
Vehicle::cur_speed
uint16 cur_speed
current speed
Definition: vehicle_base.h:307
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
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:95
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:288
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:2807
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:1162
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:357
VehicleOrderSaver::~VehicleOrderSaver
~VehicleOrderSaver()
Restore the saved order to the vehicle, if Restore() has not already been called.
Definition: train_cmd.cpp:2577
FindTrainCollideEnum
static Vehicle * FindTrainCollideEnum(Vehicle *v, void *data)
Collision test function.
Definition: train_cmd.cpp:3125
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:296
_accel_slowdown
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
Definition: train_cmd.cpp:2993
DeleteVehicleOrders
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
Definition: order_cmd.cpp:1850
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:196
OrderStopLocation
OrderStopLocation
Where to stop the trains.
Definition: order_type.h:83
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:355
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:2437
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition: track_type.h:42
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:76
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:1549
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:377
SIGTYPE_PBS
@ SIGTYPE_PBS
normal pbs signal
Definition: signal_type.h:28
GetTileTrackStatus
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
Definition: landscape.cpp:601
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition: vehicle_base.h:922
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:3172
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:90
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:77
TrainOnTileEnum
static Vehicle * TrainOnTileEnum(Vehicle *v, void *)
Check if the vehicle is a train.
Definition: train_cmd.cpp:1656
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:202
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:143
DoTrainPathfind
static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
Perform pathfinding for a train.
Definition: train_cmd.cpp:2420
Train::MarkDirty
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
Definition: train_cmd.cpp:2912
RemoveVehicleFromGroup
void RemoveVehicleFromGroup(const Vehicle *v)
Decrease the num_vehicle variable before delete an front engine from a group.
Definition: group_cmd.cpp:707
CBM_VEHICLE_LENGTH
@ CBM_VEHICLE_LENGTH
Vehicle length (trains and road vehicles)
Definition: newgrf_callbacks.h:293
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:465
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:654
SoundSettings::ambient
bool ambient
Play ambient, industry and town sounds.
Definition: settings_type.h:220
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:154
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:143
NT_ARRIVAL_COMPANY
@ NT_ARRIVAL_COMPANY
First vehicle arrived for company.
Definition: news_type.h:22
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:3167
NormaliseSubtypes
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
Definition: train_cmd.cpp:930
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:182
VRF_LEAVING_STATION
@ VRF_LEAVING_STATION
Train is just leaving a station.
Definition: train.h:33
Train::Crash
uint Crash(bool flooded=false) override
The train vehicle crashed! Update its status and other parts around it.
Definition: train_cmd.cpp:3056
ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
Definition: order_type.h:74
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:141
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:1962
Vehicle::BeginLoading
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition: vehicle.cpp:2113
GameSettings::pf
PathfinderSettings pf
settings for all pathfinders
Definition: settings_type.h:593
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:583
Vehicle::breakdown_ctr
byte breakdown_ctr
Counter for managing breakdown events.
Definition: vehicle_base.h:278
VS_HIDDEN
@ VS_HIDDEN
Vehicle is not visible.
Definition: vehicle_base.h:34
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:140
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:43
Train::OnNewDay
void OnNewDay() override
Update day counters of the train vehicle.
Definition: train_cmd.cpp:4106
PathfinderSettings::wait_twoway_signal
byte wait_twoway_signal
waitingtime in days before a twoway signal
Definition: settings_type.h:466
YapfTrainChooseTrack
Track YapfTrainChooseTrack(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool reserve_track, struct PBSTileInfo *target, TileIndex *dest)
Finds the best path for given train using YAPF.
Definition: yapf_rail.cpp:535
RailVehicleInfo
Information about a rail vehicle.
Definition: engine_type.h:42
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition: transport_type.h:27
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition: company_cmd.cpp:316
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:252
DirToDiagDir
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition: direction_func.h:166
Vehicle::HandlePathfindingResult
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition: vehicle.cpp:783
_breakdown_speeds
static const uint16 _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
Definition: train_cmd.cpp:3699
TrackBitsToTrack
static Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
Definition: track_func.h:192
return_cmd_error
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:38
IsWaitingPositionFree
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
Definition: pbs.cpp:426
MapSize
static uint MapSize()
Get the size of the map.
Definition: map_func.h:92
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition: ai_core.cpp:236
IsBridgeTile
static bool IsBridgeTile(TileIndex t)
checks if there is a bridge on this tile
Definition: bridge_map.h:35
CmdMoveRailVehicle
CommandCost CmdMoveRailVehicle(DoCommandFlag flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
Definition: train_cmd.cpp:1186
CommandCost
Common return value for all commands.
Definition: command_type.h:24
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition: track_type.h:22
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:329
CheckTrainStayInDepot
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
Definition: train_cmd.cpp:2223
CmdBuildRailVehicle
CommandCost CmdBuildRailVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, bool free_cars, Vehicle **ret)
Build a railroad vehicle.
Definition: train_cmd.cpp:742
VRF_TRAIN_STUCK
@ VRF_TRAIN_STUCK
Train can't get a path reservation.
Definition: train.h:32
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Definition: train_cmd.cpp:4144
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
UpdateTrainGroupID
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
Definition: group_cmd.cpp:749
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition: window_type.h:332
Train::UpdateDeltaXY
void UpdateDeltaXY() override
Updates the x and y offsets and the size of the sprite used for this vehicle.
Definition: train_cmd.cpp:1449
ClientSettings::sound
SoundSettings sound
sound effect settings
Definition: settings_type.h:607
Vehicle::AddToShared
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition: vehicle.cpp:2770
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:609
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:74
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:1313
INVALID_VEH_ORDER_ID
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
Definition: order_type.h:21
DIRDIFF_90LEFT
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
Definition: direction_type.h:67
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
TrackBitsToTrackdirBits
static TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition: track_func.h:318
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:258
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:245
DeleteLastWagon
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
Definition: train_cmd.cpp:3569
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:438
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:302
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:470
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:41
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:132
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:578
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:316
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:47
GetFreeUnitNumber
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition: vehicle.cpp:1806
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:392
Order::SetDestination
void SetDestination(DestinationID destination)
Sets the destination of this order.
Definition: order_base.h:111
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:324
CheckTrainsLengths
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:74
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition: command_type.h:160
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:333
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
VehicleOrderSaver::Restore
void Restore()
Restore the saved order to the vehicle.
Definition: train_cmd.cpp:2565
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:274
GroundVehicle< Train, VEH_TRAIN >::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
ScaleSpriteTrad
static int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition: zoom_func.h:107
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:65
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition: vehicle_base.h:913
ODATFB_NEAREST_DEPOT
@ ODATFB_NEAREST_DEPOT
Send the vehicle to the nearest depot.
Definition: order_type.h:105
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:54
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:4063
DiagDirToDiagTrack
static Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
Definition: track_func.h:511
DC_AUTOREPLACE
@ DC_AUTOREPLACE
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
Definition: command_type.h:364
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:146
HandleCrashedTrain
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
Definition: train_cmd.cpp:3660
TrackdirCrossesTrackdirs
static TrackdirBits TrackdirCrossesTrackdirs(Trackdir trackdir)
Maps a trackdir to all trackdirs that make 90 deg turns with it.
Definition: track_func.h:605
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:35
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:2591
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:1755
TrainApproachingLineEnd
static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
Definition: train_cmd.cpp:3712
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:572
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:741
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:277
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:317
Train
'Train' is either a loco or a wagon.
Definition: train.h:88
DiagDirToDir
static Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
Definition: direction_func.h:182
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
DEFAULT_GROUP
static const GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition: group_type.h:17
FreightWagonMult
byte FreightWagonMult(CargoID cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition: train_cmd.cpp:67
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:254
GetGRFStringID
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:601
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:380
EngineInfo::callback_mask
uint16 callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:154
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:1178
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:58
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
CmdReverseTrainDirection
CommandCost CmdReverseTrainDirection(DoCommandFlag flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
Definition: train_cmd.cpp:2004
MP_TUNNELBRIDGE
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:57
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:2161
TrainOnCrossing
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
Definition: train_cmd.cpp:1667
newgrf_text.h
INVALID_TRACKDIR
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition: track_type.h:89
CmdForceTrainProceed
CommandCost CmdForceTrainProceed(DoCommandFlag flags, VehicleID veh_id)
Force a train through a red signal.
Definition: train_cmd.cpp:2074
SoundSettings::disaster
bool disaster
Play disaster and accident sounds.
Definition: settings_type.h:218
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:1095
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:109
MarkBridgeDirty
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
Definition: tunnelbridge_cmd.cpp:66
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:2324
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:144
AccelerationSlowdownParams
Data structure for storing engine speed changes of an acceleration type.
Definition: train_cmd.cpp:2985
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:63
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:162
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:3005
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:347
RailVehicleInfo::pow_wag_power
uint16 pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
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:153
Vehicle::y_offs
int8 y_offs
y offset for vehicle sprite
Definition: vehicle_base.h:301
viewport_func.h
Vehicle::colourmap
SpriteID colourmap
NOSAVE: cached colour mapping.
Definition: vehicle_base.h:269
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:877
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:3034
UpdateLevelCrossingTile
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
Definition: train_cmd.cpp:1735
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:854
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:48
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:36
Vehicle::direction
Direction direction
facing
Definition: vehicle_base.h:286
Train::GetCurveSpeedLimit
int GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
Definition: train_cmd.cpp:305
TrainCollideChecker
Temporary data storage for testing collisions.
Definition: train_cmd.cpp:3114
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:554
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:456
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
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:3757
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:2090
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:295
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:103
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:408
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:345
_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:838
vehicle_func.h
NT_ACCIDENT
@ NT_ACCIDENT
An accident or disaster has occurred.
Definition: news_type.h:24
PROP_TRAIN_WEIGHT
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:25
AdvanceWagonsBeforeSwap
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition: train_cmd.cpp:1819
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:77
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition: sprites.h:1598
strings_func.h
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
RailVehicleInfo::max_speed
uint16 max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
Vehicle::tick_counter
byte tick_counter
Increased by one for each tick.
Definition: vehicle_base.h:329
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:322
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition: track_type.h:44
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:495
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:300
Vehicle::subspeed
byte subspeed
fractional speed
Definition: vehicle_base.h:308
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:53
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1183
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:108
Vehicle::z_extent
byte z_extent
z-extent of vehicle bounding box
Definition: vehicle_base.h:297
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
AccelerationSlowdownParams::z_up
byte z_up
Fraction to remove when moving up.
Definition: train_cmd.cpp:2988
AdvanceWagonsAfterSwap
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition: train_cmd.cpp:1847
Train::UpdateAcceleration
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
Definition: train_cmd.cpp:427
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:19
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:2529
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:365
CheckLevelCrossing
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
Definition: train_cmd.cpp:1722
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:3269
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:1273
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition: train_cmd.cpp:2342
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:1998
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:62
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:375
newgrf.h
VE_DISABLE_WAGON_POWER
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Definition: vehicle_base.h:94
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
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:272
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:307
UsesWagonOverride
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition: newgrf_engine.cpp:1147
Train::FindClosestDepot
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse) override
Locate the closest depot for this consist, and return the information to the caller.
Definition: train_cmd.cpp:2129
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:497
TrackStatusToTrackdirBits
static TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Definition: track_func.h:351
RailVehicleInfo::railtype
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
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:1681
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:464
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:3116
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:305
DifficultySettings::line_reverse_mode
bool line_reverse_mode
reversing at stations or not
Definition: settings_type.h:92
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:1173
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:485
TrainCollideChecker::v
Train * v
Vehicle we are testing for collision.
Definition: train_cmd.cpp:3115
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:125
company_func.h
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:176
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:1252
IsLevelCrossingTile
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:95
TrainCache::cached_max_curve_speed
int cached_max_curve_speed
max consist speed limited by curves
Definition: train.h:82
Engine::original_image_index
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition: engine_base.h:54
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:298
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:2987
PlayVehicleSound
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Definition: newgrf_sound.cpp:187
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:2189
Train::GetImage
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
Definition: train_cmd.cpp:491
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition: newgrf_station.cpp:954
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:134
Order::GetDepotOrderType
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition: order_base.h:145
Vehicle::InvalidateNewGRFCache
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
Definition: vehicle_base.h:478
network.h
RailVehicleInfo::shorten_factor
byte shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
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
CommandHelper
Definition: command_func.h:94
Vehicle::day_counter
byte day_counter
Increased by one for each day.
Definition: vehicle_base.h:328
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:2902
ToggleBit
static T ToggleBit(T &x, const uint8 y)
Toggles a bit in a variable.
Definition: bitmath_func.hpp:181
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:386
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:523
OrderBackup::Backup
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
Definition: order_backup.cpp:102
PathfinderSettings::yapf
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
Definition: settings_type.h:473
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:1378
Vehicle::progress
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
Definition: vehicle_base.h:311
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
Engine::DetermineCapacity
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition: engine.cpp:197
OverflowSafeInt< int64 >
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:543
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1187
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:3095
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
CCF_LENGTH
@ CCF_LENGTH
Allow vehicles to change length.
Definition: train.h:45
EF_RAIL_FLIPS
@ EF_RAIL_FLIPS
Rail vehicle has old depot-flip handling.
Definition: engine_type.h:170
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
GetTileRailType
RailType GetTileRailType(TileIndex tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition: rail.cpp:155
CmdSellRailWagon
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
Definition: train_cmd.cpp:1377
Train::GetOrderStationLocation
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
Definition: train_cmd.cpp:2897
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:320
TrainCheckIfLineEnds
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
Definition: train_cmd.cpp:3814
VehicleSettings::max_train_length
uint8 max_train_length
maximum length for trains
Definition: settings_type.h:487
Vehicle::spritenum
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition: vehicle_base.h:294
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:147
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:246
NormalizeTrainVehInDepot
static void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
Definition: train_cmd.cpp:687
SpecializedVehicle::GetLastEnginePart
T * GetLastEnginePart()
Get the last part of an articulated engine.
Definition: vehicle_base.h:1136
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:51
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:171
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:595
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:1104
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:1702
Vehicle::cargo_subtype
byte cargo_subtype
Used for livery refits (NewGRF variations)
Definition: vehicle_base.h:321
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:419
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:3545
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:416
Vehicle::GetAdvanceDistance
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
Definition: vehicle_base.h:440
RailVehicleInfo::capacity
byte capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:54
Vehicle::GetOrder
Order * GetOrder(int index) const
Returns order 'index' of a vehicle or nullptr when it doesn't exists.
Definition: vehicle_base.h:890
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
Train::Tick
bool Tick() override
Update train vehicle data for a tick.
Definition: train_cmd.cpp:4034
Vehicle::reliability
uint16 reliability
Reliability.
Definition: vehicle_base.h:276
SpecializedVehicle< Train, Type >::First
Train * First() const
Get the first vehicle in the chain.
Definition: vehicle_base.h:1080
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:1610
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:48
AS_BRAKE
@ AS_BRAKE
We want to stop.
Definition: ground_vehicle.hpp:22
Rect::Width
int Width() const
Get width of Rect.
Definition: geometry_type.hpp:79
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:1312
DecreaseVehicleValue
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition: vehicle.cpp:1250
Vehicle::y_bb_offs
int8 y_bb_offs
y offset of vehicle bounding box
Definition: vehicle_base.h:299
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:3632
TrackdirBitsToTrackBits
static TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition: track_func.h:307
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:30
MarkDirtyAdjacentLevelCrossingTiles
void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
Find adjacent level crossing tiles in this multi-track crossing and mark them dirty.
Definition: train_cmd.cpp:1788
VehicleSettings::freight_trains
uint8 freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:500
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition: geometry_type.hpp:69
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:65
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:2949
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:716
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition: vehicle_base.h:1086
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
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:336
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3180
VehicleSpriteSeq::GetBounds
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition: vehicle.cpp:98
Order::GetDepotActionType
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition: order_base.h:147
PathfinderSettings::reserve_paths
bool reserve_paths
always reserve paths regardless of signal type.
Definition: settings_type.h:468
TrainController
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
Definition: train_cmd.cpp:3224
Vehicle::first
Vehicle * first
NOSAVE: pointer to the first vehicle in the chain.
Definition: vehicle_base.h:231
IsValidTrackdir
static bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition: track_func.h:51
SpecializedVehicle::UpdateViewport
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Definition: vehicle_base.h:1205
Vehicle::fill_percent_te_id
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition: vehicle_base.h:304
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:157
Order
Definition: order_base.h:36
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:1525
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:1614
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:1124
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:261
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:604
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:40
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
Train::PlayLeaveStationSound
void PlayLeaveStationSound(bool force=false) const override
Play a sound for a train leaving the station.
Definition: train_cmd.cpp:2142
Vehicle::refit_cap
uint16 refit_cap
Capacity left over from before last refit.
Definition: vehicle_base.h:323
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:275
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:1701
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:3787
news_func.h
ReverseTrainDirection
void ReverseTrainDirection(Train *v)
Turn a train around.
Definition: train_cmd.cpp:1912
AccelerationSlowdownParams::z_down
byte z_down
Fraction to add when moving down.
Definition: train_cmd.cpp:2989
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