OpenTTD Source: src/train_cmd.cpp Source File

OpenTTD Source 15.3

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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "error.h"
12#include "articulated_vehicles.h"
13#include "command_func.h"
14#include "error_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 "core/random_func.hpp"
30#include "company_base.h"
31#include "newgrf.h"
32#include "order_backup.h"
33#include "zoom_func.h"
34#include "newgrf_debug.h"
35#include "framerate_type.h"
36#include "train_cmd.h"
37#include "misc_cmd.h"
38#include "timer/timer_game_calendar.h"
39#include "timer/timer_game_economy.h"
40
41#include "table/strings.h"
42#include "table/train_sprites.h"
43
44#include "safeguards.h"
45
46static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck);
47static bool TrainCheckIfLineEnds(Train *v, bool reverse = true);
48bool TrainController(Train *v, Vehicle *nomove, bool reverse = true); // Also used in vehicle_sl.cpp.
49static TileIndex TrainApproachingCrossingTile(const Train *v);
50static void CheckIfTrainNeedsService(Train *v);
51static void CheckNextTrainTile(Train *v);
52
53static const uint8_t _vehicle_initial_x_fract[4] = {10, 8, 4, 8};
54static const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
55
56template <>
57bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
58{
59 return image_index < lengthof(_engine_sprite_base);
60}
61
62
68uint8_t FreightWagonMult(CargoType cargo)
69{
70 if (!CargoSpec::Get(cargo)->is_freight) return 1;
71 return _settings_game.vehicle.freight_trains;
72}
73
75 void CheckTrainsLengths()
76{
77 bool first = true;
78
79 for (const Train *v : Train::Iterate()) {
80 if (v->First() == v && !v->vehstatus.Test(VehState::Crashed)) {
81 for (const Train *u = v, *w = v->Next(); w != nullptr; u = w, w = w->Next()) {
82 if (u->track != TRACK_BIT_DEPOT) {
83 if ((w->track != TRACK_BIT_DEPOT &&
84 std::max(abs(u->x_pos - w->x_pos), abs(u->y_pos - w->y_pos)) != u->CalcNextVehicleOffset()) ||
85 (w->track == TRACK_BIT_DEPOT && TicksToLeaveDepot(u) <= 0)) {
86 ShowErrorMessage(GetEncodedString(STR_BROKEN_VEHICLE_LENGTH, v->index, v->owner), {}, WL_CRITICAL);
87
88 if (!_networking && first) {
89 first = false;
90 Command<CMD_PAUSE>::Post(PauseMode::Error, true);
91 }
92 /* Break so we warn only once for each train. */
93 break;
94 }
95 }
96 }
97 }
98 }
99}
100
107 void Train::ConsistChanged(ConsistChangeFlags allowed_changes)
108{
109 uint16_t max_speed = UINT16_MAX;
110
111 assert(this->IsFrontEngine() || this->IsFreeWagon());
112
113 const RailVehicleInfo *rvi_v = RailVehInfo(this->engine_type);
114 EngineID first_engine = this->IsFrontEngine() ? this->engine_type : EngineID::Invalid();
115 this->gcache.cached_total_length = 0;
116 this->compatible_railtypes = {};
117
118 bool train_can_tilt = true;
119 int16_t min_curve_speed_mod = INT16_MAX;
120
121 for (Train *u = this; u != nullptr; u = u->Next()) {
122 const RailVehicleInfo *rvi_u = RailVehInfo(u->engine_type);
123
124 /* Check the this->first cache. */
125 assert(u->First() == this);
126
127 /* update the 'first engine' */
128 u->gcache.first_engine = this == u ? EngineID::Invalid() : first_engine;
129 u->railtypes = rvi_u->railtypes;
130
131 if (u->IsEngine()) first_engine = u->engine_type;
132
133 /* Set user defined data to its default value */
134 u->tcache.user_def_data = rvi_u->user_def_data;
135 this->InvalidateNewGRFCache();
136 u->InvalidateNewGRFCache();
137 }
138
139 for (Train *u = this; u != nullptr; u = u->Next()) {
140 /* Update user defined data (must be done before other properties) */
141 u->tcache.user_def_data = GetVehicleProperty(u, PROP_TRAIN_USER_DATA, u->tcache.user_def_data);
142 this->InvalidateNewGRFCache();
143 u->InvalidateNewGRFCache();
144 }
145
146 for (Train *u = this; u != nullptr; u = u->Next()) {
147 const Engine *e_u = u->GetEngine();
148 const RailVehicleInfo *rvi_u = &e_u->VehInfo<RailVehicleInfo>();
149
150 if (!e_u->info.misc_flags.Test(EngineMiscFlag::RailTilts)) train_can_tilt = false;
151 min_curve_speed_mod = std::min(min_curve_speed_mod, u->GetCurveSpeedModifier());
152
153 /* Cache wagon override sprite group. nullptr is returned if there is none */
154 u->tcache.cached_override = GetWagonOverrideSpriteSet(u->engine_type, u->cargo_type, u->gcache.first_engine);
155
156 /* Reset colour map */
157 u->colourmap = PAL_NONE;
158
159 /* Update powered-wagon-status and visual effect */
160 u->UpdateVisualEffect(true);
161
162 if (rvi_v->pow_wag_power != 0 && rvi_u->railveh_type == RAILVEH_WAGON &&
163 UsesWagonOverride(u) && !HasBit(u->vcache.cached_vis_effect, VE_DISABLE_WAGON_POWER)) {
164 /* wagon is powered */
165 u->flags.Set(VehicleRailFlag::PoweredWagon); // cache 'powered' status
166 } else {
167 u->flags.Reset(VehicleRailFlag::PoweredWagon);
168 }
169
170 if (!u->IsArticulatedPart()) {
171 /* Do not count powered wagons for the compatible railtypes, as wagons always
172 have railtype normal */
173 if (rvi_u->power > 0) {
174 this->compatible_railtypes.Set(GetAllPoweredRailTypes(u->railtypes));
175 }
176
177 /* Some electric engines can be allowed to run on normal rail. It happens to all
178 * existing electric engines when elrails are disabled and then re-enabled */
179 if (u->flags.Test(VehicleRailFlag::AllowedOnNormalRail)) {
180 u->railtypes.Set(RAILTYPE_RAIL);
181 u->compatible_railtypes.Set(RAILTYPE_RAIL);
182 }
183
184 /* max speed is the minimum of the speed limits of all vehicles in the consist */
185 if ((rvi_u->railveh_type != RAILVEH_WAGON || _settings_game.vehicle.wagon_speed_limits) && !UsesWagonOverride(u)) {
186 uint16_t speed = GetVehicleProperty(u, PROP_TRAIN_SPEED, rvi_u->max_speed);
187 if (speed != 0) max_speed = std::min(speed, max_speed);
188 }
189 }
190
191 uint16_t new_cap = e_u->DetermineCapacity(u);
192 if (allowed_changes.Test(ConsistChangeFlag::Capacity)) {
193 /* Update vehicle capacity. */
194 if (u->cargo_cap > new_cap) u->cargo.Truncate(new_cap);
195 u->refit_cap = std::min(new_cap, u->refit_cap);
196 u->cargo_cap = new_cap;
197 } else {
198 /* Verify capacity hasn't changed. */
199 if (new_cap != u->cargo_cap) ShowNewGrfVehicleError(u->engine_type, STR_NEWGRF_BROKEN, STR_NEWGRF_BROKEN_CAPACITY, GRFBug::VehCapacity, true);
200 }
201 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_TRAIN_CARGO_AGE_PERIOD, e_u->info.cargo_age_period);
202
203 /* check the vehicle length (callback) */
204 uint16_t veh_len = CALLBACK_FAILED;
205 if (e_u->GetGRF() != nullptr && e_u->GetGRF()->grf_version >= 8) {
206 /* Use callback 36 */
207 veh_len = GetVehicleProperty(u, PROP_TRAIN_SHORTEN_FACTOR, CALLBACK_FAILED);
208
209 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) {
210 ErrorUnknownCallbackResult(e_u->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
211 }
212 } else if (e_u->info.callback_mask.Test(VehicleCallbackMask::Length)) {
213 /* Use callback 11 */
214 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, u->engine_type, u);
215 }
216 if (veh_len == CALLBACK_FAILED) veh_len = rvi_u->shorten_factor;
217 veh_len = VEHICLE_LENGTH - Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
218
219 if (allowed_changes.Test(ConsistChangeFlag::Length)) {
220 /* Update vehicle length. */
221 u->gcache.cached_veh_length = veh_len;
222 } else {
223 /* Verify length hasn't changed. */
224 if (veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
225 }
226
227 this->gcache.cached_total_length += u->gcache.cached_veh_length;
228 this->InvalidateNewGRFCache();
229 u->InvalidateNewGRFCache();
230 }
231
232 /* store consist weight/max speed in cache */
233 this->vcache.cached_max_speed = max_speed;
234 this->tcache.cached_tilt = train_can_tilt;
235 this->tcache.cached_curve_speed_mod = min_curve_speed_mod;
236 this->tcache.cached_max_curve_speed = this->GetCurveSpeedLimit();
237
238 /* 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) */
239 this->CargoChanged();
240
241 if (this->IsFrontEngine()) {
242 this->UpdateAcceleration();
243 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
244 InvalidateWindowData(WC_VEHICLE_REFIT, this->index, VIWD_CONSIST_CHANGED);
245 InvalidateWindowData(WC_VEHICLE_ORDERS, this->index, VIWD_CONSIST_CHANGED);
246 InvalidateNewGRFInspectWindow(GSF_TRAINS, this->index);
247
248 /* If the consist is changed while in a depot, the vehicle view window must be invalidated to update the availability of refitting. */
249 InvalidateWindowData(WC_VEHICLE_VIEW, this->index, VIWD_CONSIST_CHANGED);
250 }
251}
252
263 int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *v, int *station_ahead, int *station_length)
264{
265 const Station *st = Station::Get(station_id);
266 *station_ahead = st->GetPlatformLength(tile, DirToDiagDir(v->direction)) * TILE_SIZE;
267 *station_length = st->GetPlatformLength(tile) * TILE_SIZE;
268
269 /* Default to the middle of the station for stations stops that are not in
270 * the order list like intermediate stations when non-stop is disabled */
271 OrderStopLocation osl = OrderStopLocation::Middle;
272 if (v->gcache.cached_total_length >= *station_length) {
273 /* The train is longer than the station, make it stop at the far end of the platform */
274 osl = OrderStopLocation::FarEnd;
275 } else if (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == station_id) {
276 osl = v->current_order.GetStopLocation();
277 }
278
279 /* The stop location of the FRONT! of the train */
280 int stop;
281 switch (osl) {
282 default: NOT_REACHED();
283
284 case OrderStopLocation::NearEnd:
285 stop = v->gcache.cached_total_length;
286 break;
287
288 case OrderStopLocation::Middle:
289 stop = *station_length - (*station_length - v->gcache.cached_total_length) / 2;
290 break;
291
292 case OrderStopLocation::FarEnd:
293 stop = *station_length;
294 break;
295 }
296
297 /* Subtract half the front vehicle length of the train so we get the real
298 * stop location of the train. */
299 return stop - (v->gcache.cached_veh_length + 1) / 2;
300}
301
302
307uint16_t Train::GetCurveSpeedLimit() const
308{
309 assert(this->First() == this);
310
311 static const int absolute_max_speed = UINT16_MAX;
312 int max_speed = absolute_max_speed;
313
314 if (_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) return max_speed;
315
316 int curvecount[2] = {0, 0};
317
318 /* first find the curve speed limit */
319 int numcurve = 0;
320 int sum = 0;
321 int pos = 0;
322 int lastpos = -1;
323 for (const Train *u = this; u->Next() != nullptr; u = u->Next(), pos += u->gcache.cached_veh_length) {
324 Direction this_dir = u->direction;
325 Direction next_dir = u->Next()->direction;
326
327 DirDiff dirdiff = DirDifference(this_dir, next_dir);
328 if (dirdiff == DIRDIFF_SAME) continue;
329
330 if (dirdiff == DIRDIFF_45LEFT) curvecount[0]++;
331 if (dirdiff == DIRDIFF_45RIGHT) curvecount[1]++;
332 if (dirdiff == DIRDIFF_45LEFT || dirdiff == DIRDIFF_45RIGHT) {
333 if (lastpos != -1) {
334 numcurve++;
335 sum += pos - lastpos;
336 if (pos - lastpos <= static_cast<int>(VEHICLE_LENGTH) && max_speed > 88) {
337 max_speed = 88;
338 }
339 }
340 lastpos = pos;
341 }
342
343 /* if we have a 90 degree turn, fix the speed limit to 60 */
344 if (dirdiff == DIRDIFF_90LEFT || dirdiff == DIRDIFF_90RIGHT) {
345 max_speed = 61;
346 }
347 }
348
349 if (numcurve > 0 && max_speed > 88) {
350 if (curvecount[0] == 1 && curvecount[1] == 1) {
351 max_speed = absolute_max_speed;
352 } else {
353 sum = CeilDiv(sum, VEHICLE_LENGTH);
354 sum /= numcurve;
355 max_speed = 232 - (13 - Clamp(sum, 1, 12)) * (13 - Clamp(sum, 1, 12));
356 }
357 }
358
359 if (max_speed != absolute_max_speed) {
360 /* Apply the current railtype's curve speed advantage */
361 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(this->tile));
362 max_speed += (max_speed / 2) * rti->curve_speed;
363
364 if (this->tcache.cached_tilt) {
365 /* Apply max_speed bonus of 20% for a tilting train */
366 max_speed += max_speed / 5;
367 }
368
369 /* Apply max_speed modifier (cached value is fixed-point binary with 8 fractional bits)
370 * and clamp the result to an acceptable range. */
371 max_speed += (max_speed * this->tcache.cached_curve_speed_mod) / 256;
372 max_speed = Clamp(max_speed, 2, absolute_max_speed);
373 }
374
375 return static_cast<uint16_t>(max_speed);
376}
377
382 int Train::GetCurrentMaxSpeed() const
383{
384 int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
385 this->gcache.cached_max_track_speed :
386 this->tcache.cached_max_curve_speed;
387
388 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && IsRailStationTile(this->tile)) {
389 StationID sid = GetStationIndex(this->tile);
390 if (this->current_order.ShouldStopAtStation(this, sid)) {
391 int station_ahead;
392 int station_length;
393 int stop_at = GetTrainStopLocation(sid, this->tile, this, &station_ahead, &station_length);
394
395 /* The distance to go is whatever is still ahead of the train minus the
396 * distance from the train's stop location to the end of the platform */
397 int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
398
399 if (distance_to_go > 0) {
400 int st_max_speed = 120;
401
402 int delta_v = this->cur_speed / (distance_to_go + 1);
403 if (max_speed > (this->cur_speed - delta_v)) {
404 st_max_speed = this->cur_speed - (delta_v / 10);
405 }
406
407 st_max_speed = std::max(st_max_speed, 25 * distance_to_go);
408 max_speed = std::min(max_speed, st_max_speed);
409 }
410 }
411 }
412
413 for (const Train *u = this; u != nullptr; u = u->Next()) {
414 if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
415 max_speed = std::min(max_speed, 61);
416 break;
417 }
418
419 /* Vehicle is on the middle part of a bridge. */
420 if (u->track == TRACK_BIT_WORMHOLE && !u->vehstatus.Test(VehState::Hidden)) {
421 max_speed = std::min<int>(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed);
422 }
423 }
424
425 max_speed = std::min<int>(max_speed, this->current_order.GetMaxSpeed());
426 return std::min<int>(max_speed, this->gcache.cached_max_track_speed);
427}
428
430 void Train::UpdateAcceleration()
431{
432 assert(this->IsFrontEngine() || this->IsFreeWagon());
433
434 uint power = this->gcache.cached_power;
435 uint weight = this->gcache.cached_weight;
436 assert(weight != 0);
437 this->acceleration = Clamp(power / weight * 4, 1, 255);
438}
439
440int Train::GetCursorImageOffset() const
441{
442 if (this->gcache.cached_veh_length != 8 && this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
443 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
444
445 const Engine *e = this->GetEngine();
446 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->VehInfo<RailVehicleInfo>().image_index)) {
447 reference_width = e->GetGRF()->traininfo_vehicle_width;
448 }
449
450 return ScaleSpriteTrad((this->gcache.cached_veh_length - (int)VEHICLE_LENGTH) * reference_width / (int)VEHICLE_LENGTH);
451 }
452 return 0;
453}
454
460 int Train::GetDisplayImageWidth(Point *offset) const
461{
462 int reference_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
463 int vehicle_pitch = 0;
464
465 const Engine *e = this->GetEngine();
466 if (e->GetGRF() != nullptr && IsCustomVehicleSpriteNum(e->VehInfo<RailVehicleInfo>().image_index)) {
467 reference_width = e->GetGRF()->traininfo_vehicle_width;
468 vehicle_pitch = e->GetGRF()->traininfo_vehicle_pitch;
469 }
470
471 if (offset != nullptr) {
472 if (this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips)) {
473 offset->x = ScaleSpriteTrad(((int)this->gcache.cached_veh_length - (int)VEHICLE_LENGTH / 2) * reference_width / (int)VEHICLE_LENGTH);
474 } else {
475 offset->x = ScaleSpriteTrad(reference_width) / 2;
476 }
477 offset->y = ScaleSpriteTrad(vehicle_pitch);
478 }
479 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
480}
481
482static SpriteID GetDefaultTrainSprite(uint8_t spritenum, Direction direction)
483{
484 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
485 return ((direction + _engine_sprite_add[spritenum]) & _engine_sprite_and[spritenum]) + _engine_sprite_base[spritenum];
486}
487
494 void Train::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
495{
496 uint8_t spritenum = this->spritenum;
497
498 if (this->flags.Test(VehicleRailFlag::Flipped)) direction = ReverseDir(direction);
499
500 if (IsCustomVehicleSpriteNum(spritenum)) {
501 if (spritenum == CUSTOM_VEHICLE_SPRITENUM_REVERSED) direction = ReverseDir(direction);
502 GetCustomVehicleSprite(this, direction, image_type, result);
503 if (result->IsValid()) return;
504
505 spritenum = this->GetEngine()->original_image_index;
506 }
507
508 assert(IsValidImageIndex<VEH_TRAIN>(spritenum));
509 SpriteID sprite = GetDefaultTrainSprite(spritenum, direction);
510
511 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _wagon_full_adder[spritenum];
512
513 result->Set(sprite);
514}
515
516static void GetRailIcon(EngineID engine, bool rear_head, int &y, EngineImageType image_type, VehicleSpriteSeq *result)
517{
518 const Engine *e = Engine::Get(engine);
519 Direction dir = rear_head ? DIR_E : DIR_W;
520 uint8_t spritenum = e->VehInfo<RailVehicleInfo>().image_index;
521
522 if (IsCustomVehicleSpriteNum(spritenum)) {
523 GetCustomVehicleIcon(engine, dir, image_type, result);
524 if (result->IsValid()) {
525 if (e->GetGRF() != nullptr) {
526 y += ScaleSpriteTrad(e->GetGRF()->traininfo_vehicle_pitch);
527 }
528 return;
529 }
530
531 spritenum = Engine::Get(engine)->original_image_index;
532 }
533
534 if (rear_head) spritenum++;
535
536 result->Set(GetDefaultTrainSprite(spritenum, DIR_W));
537}
538
539void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
540{
541 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
542 int yf = y;
543 int yr = y;
544
545 VehicleSpriteSeq seqf, seqr;
546 GetRailIcon(engine, false, yf, image_type, &seqf);
547 GetRailIcon(engine, true, yr, image_type, &seqr);
548
549 Rect rectf, rectr;
550 seqf.GetBounds(&rectf);
551 seqr.GetBounds(&rectr);
552
553 preferred_x = Clamp(preferred_x,
554 left - UnScaleGUI(rectf.left) + ScaleSpriteTrad(14),
555 right - UnScaleGUI(rectr.right) - ScaleSpriteTrad(15));
556
557 seqf.Draw(preferred_x - ScaleSpriteTrad(14), yf, pal, pal == PALETTE_CRASH);
558 seqr.Draw(preferred_x + ScaleSpriteTrad(15), yr, pal, pal == PALETTE_CRASH);
559 } else {
560 VehicleSpriteSeq seq;
561 GetRailIcon(engine, false, y, image_type, &seq);
562
563 Rect rect;
564 seq.GetBounds(&rect);
565 preferred_x = Clamp(preferred_x,
566 left - UnScaleGUI(rect.left),
567 right - UnScaleGUI(rect.right));
568
569 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
570 }
571}
572
582 void GetTrainSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
583{
584 int y = 0;
585
586 VehicleSpriteSeq seq;
587 GetRailIcon(engine, false, y, image_type, &seq);
588
589 Rect rect;
590 seq.GetBounds(&rect);
591
592 width = UnScaleGUI(rect.Width());
593 height = UnScaleGUI(rect.Height());
594 xoffs = UnScaleGUI(rect.left);
595 yoffs = UnScaleGUI(rect.top);
596
597 if (RailVehInfo(engine)->railveh_type == RAILVEH_MULTIHEAD) {
598 GetRailIcon(engine, true, y, image_type, &seq);
599 seq.GetBounds(&rect);
600
601 /* Calculate values relative to an imaginary center between the two sprites. */
602 width = ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) + UnScaleGUI(rect.right) - xoffs;
603 height = std::max<uint>(height, UnScaleGUI(rect.Height()));
604 xoffs = xoffs - ScaleSpriteTrad(TRAININFO_DEFAULT_VEHICLE_WIDTH) / 2;
605 yoffs = std::min(yoffs, UnScaleGUI(rect.top));
606 }
607}
608
614 static std::vector<VehicleID> GetFreeWagonsInDepot(TileIndex tile)
615{
616 std::vector<VehicleID> free_wagons;
617
618 for (Vehicle *v : VehiclesOnTile(tile)) {
619 if (v->type != VEH_TRAIN) continue;
620 if (v->vehstatus.Test(VehState::Crashed)) continue;
621 if (!Train::From(v)->IsFreeWagon()) continue;
622
623 free_wagons.push_back(v->index);
624 }
625
626 /* Sort by vehicle index for consistency across clients. */
627 std::ranges::sort(free_wagons);
628 return free_wagons;
629}
630
639 static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
640{
641 const RailVehicleInfo *rvi = &e->VehInfo<RailVehicleInfo>();
642
643 /* Check that the wagon can drive on the track in question */
644 if (!IsCompatibleRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR;
645
646 if (flags.Test(DoCommandFlag::Execute)) {
647 Train *v = new Train();
648 *ret = v;
649 v->spritenum = rvi->image_index;
650
651 v->engine_type = e->index;
652 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
653
654 DiagDirection dir = GetRailDepotDirection(tile);
655
656 v->direction = DiagDirToDir(dir);
657 v->tile = tile;
658
659 int x = TileX(tile) * TILE_SIZE | _vehicle_initial_x_fract[dir];
660 int y = TileY(tile) * TILE_SIZE | _vehicle_initial_y_fract[dir];
661
662 v->x_pos = x;
663 v->y_pos = y;
664 v->z_pos = GetSlopePixelZ(x, y, true);
665 v->owner = _current_company;
666 v->track = TRACK_BIT_DEPOT;
667 v->vehstatus = {VehState::Hidden, VehState::DefaultPalette};
668
669 v->SetWagon();
670
671 v->SetFreeWagon();
672 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
673
674 v->cargo_type = e->GetDefaultCargoType();
675 assert(IsValidCargoType(v->cargo_type));
676 v->cargo_cap = rvi->capacity;
677 v->refit_cap = 0;
678
679 v->railtypes = rvi->railtypes;
680
681 v->date_of_last_service = TimerGameEconomy::date;
682 v->date_of_last_service_newgrf = TimerGameCalendar::date;
683 v->build_year = TimerGameCalendar::year;
684 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
685 v->random_bits = Random();
686
687 v->group_id = DEFAULT_GROUP;
688
689 auto prob = TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed);
690 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
691 AddArticulatedParts(v);
692
693 v->UpdatePosition();
694 v->First()->ConsistChanged(CCF_ARRANGE);
695 UpdateTrainGroupID(v->First());
696
697 CheckConsistencyOfArticulatedVehicle(v);
698
699 /* Try to connect the vehicle to one of free chains of wagons. */
700 for (VehicleID vehicle : GetFreeWagonsInDepot(tile)) {
701 if (vehicle == v->index) continue;
702
703 const Train *w = Train::Get(vehicle);
704 if (w->engine_type != v->engine_type) continue;
705 if (w->First() == v) continue;
706
707 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DoCommandFlag::Execute, v->index, w->Last()->index, true).Succeeded()) {
708 break;
709 }
710 }
711 }
712
713 return CommandCost();
714}
715
717 void NormalizeTrainVehInDepot(const Train *u)
718{
719 assert(u->IsEngine());
720 for (VehicleID vehicle : GetFreeWagonsInDepot(u->tile)) {
721 if (Command<CMD_MOVE_RAIL_VEHICLE>::Do(DoCommandFlag::Execute, vehicle, u->index, true).Failed()) {
722 break;
723 }
724 }
725}
726
727static void AddRearEngineToMultiheadedTrain(Train *v)
728{
729 Train *u = new Train();
730 v->value >>= 1;
731 u->value = v->value;
732 u->direction = v->direction;
733 u->owner = v->owner;
734 u->tile = v->tile;
735 u->x_pos = v->x_pos;
736 u->y_pos = v->y_pos;
737 u->z_pos = v->z_pos;
738 u->track = TRACK_BIT_DEPOT;
739 u->vehstatus = v->vehstatus;
740 u->vehstatus.Reset(VehState::Stopped);
741 u->spritenum = v->spritenum + 1;
742 u->cargo_type = v->cargo_type;
743 u->cargo_subtype = v->cargo_subtype;
744 u->cargo_cap = v->cargo_cap;
745 u->refit_cap = v->refit_cap;
746 u->railtypes = v->railtypes;
747 u->engine_type = v->engine_type;
748 u->date_of_last_service = v->date_of_last_service;
749 u->date_of_last_service_newgrf = v->date_of_last_service_newgrf;
750 u->build_year = v->build_year;
751 u->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
752 u->random_bits = Random();
753 v->SetMultiheaded();
754 u->SetMultiheaded();
755 v->SetNext(u);
756 auto prob = TestVehicleBuildProbability(u, u->engine_type, BuildProbabilityType::Reversed);
757 if (prob.has_value()) u->flags.Set(VehicleRailFlag::Flipped, prob.value());
758 u->UpdatePosition();
759
760 /* Now we need to link the front and rear engines together */
761 v->other_multiheaded_part = u;
762 u->other_multiheaded_part = v;
763}
764
773 CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
774{
775 const RailVehicleInfo *rvi = &e->VehInfo<RailVehicleInfo>();
776
777 if (rvi->railveh_type == RAILVEH_WAGON) return CmdBuildRailWagon(flags, tile, e, ret);
778
779 /* Check if depot and new engine uses the same kind of tracks *
780 * We need to see if the engine got power on the tile to avoid electric engines in non-electric depots */
781 if (!HasPowerOnRail(rvi->railtypes, GetRailType(tile))) return CMD_ERROR;
782
783 if (flags.Test(DoCommandFlag::Execute)) {
784 DiagDirection dir = GetRailDepotDirection(tile);
785 int x = TileX(tile) * TILE_SIZE + _vehicle_initial_x_fract[dir];
786 int y = TileY(tile) * TILE_SIZE + _vehicle_initial_y_fract[dir];
787
788 Train *v = new Train();
789 *ret = v;
790 v->direction = DiagDirToDir(dir);
791 v->tile = tile;
792 v->owner = _current_company;
793 v->x_pos = x;
794 v->y_pos = y;
795 v->z_pos = GetSlopePixelZ(x, y, true);
796 v->track = TRACK_BIT_DEPOT;
797 v->vehstatus = {VehState::Hidden, VehState::Stopped, VehState::DefaultPalette};
798 v->spritenum = rvi->image_index;
799 v->cargo_type = e->GetDefaultCargoType();
800 assert(IsValidCargoType(v->cargo_type));
801 v->cargo_cap = rvi->capacity;
802 v->refit_cap = 0;
803 v->last_station_visited = StationID::Invalid();
804 v->last_loading_station = StationID::Invalid();
805
806 v->engine_type = e->index;
807 v->gcache.first_engine = EngineID::Invalid(); // needs to be set before first callback
808
809 v->reliability = e->reliability;
810 v->reliability_spd_dec = e->reliability_spd_dec;
811 v->max_age = e->GetLifeLengthInDays();
812
813 v->railtypes = rvi->railtypes;
814
815 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_trains);
816 v->date_of_last_service = TimerGameEconomy::date;
817 v->date_of_last_service_newgrf = TimerGameCalendar::date;
818 v->build_year = TimerGameCalendar::year;
819 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
820 v->random_bits = Random();
821
822 if (e->flags.Test(EngineFlag::ExclusivePreview)) v->vehicle_flags.Set(VehicleFlag::BuiltAsPrototype);
823 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
824
825 v->group_id = DEFAULT_GROUP;
826
827 v->SetFrontEngine();
828 v->SetEngine();
829
830 auto prob = TestVehicleBuildProbability(v, v->engine_type, BuildProbabilityType::Reversed);
831 if (prob.has_value()) v->flags.Set(VehicleRailFlag::Flipped, prob.value());
832 v->UpdatePosition();
833
834 if (rvi->railveh_type == RAILVEH_MULTIHEAD) {
835 AddRearEngineToMultiheadedTrain(v);
836 } else {
837 AddArticulatedParts(v);
838 }
839
840 v->ConsistChanged(CCF_ARRANGE);
841 UpdateTrainGroupID(v);
842
843 CheckConsistencyOfArticulatedVehicle(v);
844 }
845
846 return CommandCost();
847}
848
849static Train *FindGoodVehiclePos(const Train *src)
850{
851 EngineID eng = src->engine_type;
852
853 for (VehicleID vehicle : GetFreeWagonsInDepot(src->tile)) {
854 Train *dst = Train::Get(vehicle);
855
856 /* check so all vehicles in the line have the same engine. */
857 Train *t = dst;
858 while (t->engine_type == eng) {
859 t = t->Next();
860 if (t == nullptr) return dst;
861 }
862 }
863
864 return nullptr;
865}
866
868 typedef std::vector<Train *> TrainList;
869
875 static void MakeTrainBackup(TrainList &list, Train *t)
876{
877 for (; t != nullptr; t = t->Next()) list.push_back(t);
878}
879
884 static void RestoreTrainBackup(TrainList &list)
885{
886 /* No train, nothing to do. */
887 if (list.empty()) return;
888
889 Train *prev = nullptr;
890 /* Iterate over the list and rebuild it. */
891 for (Train *t : list) {
892 if (prev != nullptr) {
893 prev->SetNext(t);
894 } else if (t->Previous() != nullptr) {
895 /* Make sure the head of the train is always the first in the chain. */
896 t->Previous()->SetNext(nullptr);
897 }
898 prev = t;
899 }
900}
901
907 static void RemoveFromConsist(Train *part, bool chain = false)
908{
909 Train *tail = chain ? part->Last() : part->GetLastEnginePart();
910
911 /* Unlink at the front, but make it point to the next
912 * vehicle after the to be remove part. */
913 if (part->Previous() != nullptr) part->Previous()->SetNext(tail->Next());
914
915 /* Unlink at the back */
916 tail->SetNext(nullptr);
917}
918
924 static void InsertInConsist(Train *dst, Train *chain)
925{
926 /* We do not want to add something in the middle of an articulated part. */
927 assert(dst != nullptr && (dst->Next() == nullptr || !dst->Next()->IsArticulatedPart()));
928
929 chain->Last()->SetNext(dst->Next());
930 dst->SetNext(chain);
931}
932
938 static void NormaliseDualHeads(Train *t)
939{
940 for (; t != nullptr; t = t->GetNextVehicle()) {
941 if (!t->IsMultiheaded() || !t->IsEngine()) continue;
942
943 /* Make sure that there are no free cars before next engine */
944 Train *u;
945 for (u = t; u->Next() != nullptr && !u->Next()->IsEngine(); u = u->Next()) {}
946
947 if (u == t->other_multiheaded_part) continue;
948
949 /* Remove the part from the 'wrong' train */
950 RemoveFromConsist(t->other_multiheaded_part);
951 /* And add it to the 'right' train */
952 InsertInConsist(u, t->other_multiheaded_part);
953 }
954}
955
960 static void NormaliseSubtypes(Train *chain)
961{
962 /* Nothing to do */
963 if (chain == nullptr) return;
964
965 /* We must be the first in the chain. */
966 assert(chain->Previous() == nullptr);
967
968 /* Set the appropriate bits for the first in the chain. */
969 if (chain->IsWagon()) {
970 chain->SetFreeWagon();
971 } else {
972 assert(chain->IsEngine());
973 chain->SetFrontEngine();
974 }
975
976 /* Now clear the bits for the rest of the chain */
977 for (Train *t = chain->Next(); t != nullptr; t = t->Next()) {
978 t->ClearFreeWagon();
979 t->ClearFrontEngine();
980 }
981}
982
992 static CommandCost CheckNewTrain(Train *original_dst, Train *dst, Train *original_src, Train *src)
993{
994 /* Just add 'new' engines and subtract the original ones.
995 * If that's less than or equal to 0 we can be sure we did
996 * not add any engines (read: trains) along the way. */
997 if ((src != nullptr && src->IsEngine() ? 1 : 0) +
998 (dst != nullptr && dst->IsEngine() ? 1 : 0) -
999 (original_src != nullptr && original_src->IsEngine() ? 1 : 0) -
1000 (original_dst != nullptr && original_dst->IsEngine() ? 1 : 0) <= 0) {
1001 return CommandCost();
1002 }
1003
1004 /* Get a free unit number and check whether it's within the bounds.
1005 * There will always be a maximum of one new train. */
1006 if (GetFreeUnitNumber(VEH_TRAIN) <= _settings_game.vehicle.max_trains) return CommandCost();
1007
1008 return CommandCost(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
1009}
1010
1016 static CommandCost CheckTrainAttachment(Train *t)
1017{
1018 /* No multi-part train, no need to check. */
1019 if (t == nullptr || t->Next() == nullptr) return CommandCost();
1020
1021 /* The maximum length for a train. For each part we decrease this by one
1022 * and if the result is negative the train is simply too long. */
1023 int allowed_len = _settings_game.vehicle.max_train_length * TILE_SIZE - t->gcache.cached_veh_length;
1024
1025 /* For free-wagon chains, check if they are within the max_train_length limit. */
1026 if (!t->IsEngine()) {
1027 t = t->Next();
1028 while (t != nullptr) {
1029 allowed_len -= t->gcache.cached_veh_length;
1030
1031 t = t->Next();
1032 }
1033
1034 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1035 return CommandCost();
1036 }
1037
1038 Train *head = t;
1039 Train *prev = t;
1040
1041 /* Break the prev -> t link so it always holds within the loop. */
1042 t = t->Next();
1043 prev->SetNext(nullptr);
1044
1045 /* Make sure the cache is cleared. */
1046 head->InvalidateNewGRFCache();
1047
1048 while (t != nullptr) {
1049 allowed_len -= t->gcache.cached_veh_length;
1050
1051 Train *next = t->Next();
1052
1053 /* Unlink the to-be-added piece; it is already unlinked from the previous
1054 * part due to the fact that the prev -> t link is broken. */
1055 t->SetNext(nullptr);
1056
1057 /* Don't check callback for articulated or rear dual headed parts */
1058 if (!t->IsArticulatedPart() && !t->IsRearDualheaded()) {
1059 /* Back up and clear the first_engine data to avoid using wagon override group */
1060 EngineID first_engine = t->gcache.first_engine;
1061 t->gcache.first_engine = EngineID::Invalid();
1062
1063 /* We don't want the cache to interfere. head's cache is cleared before
1064 * the loop and after each callback does not need to be cleared here. */
1065 t->InvalidateNewGRFCache();
1066
1067 std::array<int32_t, 1> regs100;
1068 uint16_t callback = GetVehicleCallbackParent(CBID_TRAIN_ALLOW_WAGON_ATTACH, 0, 0, head->engine_type, t, head, regs100);
1069
1070 /* Restore original first_engine data */
1071 t->gcache.first_engine = first_engine;
1072
1073 /* We do not want to remember any cached variables from the test run */
1074 t->InvalidateNewGRFCache();
1075 head->InvalidateNewGRFCache();
1076
1077 if (callback != CALLBACK_FAILED) {
1078 /* A failing callback means everything is okay */
1079 StringID error = STR_NULL;
1080
1081 if (head->GetGRF()->grf_version < 8) {
1082 if (callback == 0xFD) error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1083 if (callback < 0xFD) error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1084 if (callback >= 0x100) ErrorUnknownCallbackResult(head->GetGRFID(), CBID_TRAIN_ALLOW_WAGON_ATTACH, callback);
1085 } else {
1086 if (callback < 0x400) {
1087 error = GetGRFStringID(head->GetGRFID(), GRFSTR_MISC_GRF_TEXT + callback);
1088 } else {
1089 switch (callback) {
1090 case 0x400: // allow if railtypes match (always the case for OpenTTD)
1091 case 0x401: // allow
1092 break;
1093
1094 case 0x40F:
1095 error = GetGRFStringID(head->GetGRFID(), static_cast<GRFStringID>(regs100[0]));
1096 break;
1097
1098 default: // unknown reason -> disallow
1099 case 0x402: // disallow attaching
1100 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
1101 break;
1102 }
1103 }
1104 }
1105
1106 if (error != STR_NULL) return CommandCost(error);
1107 }
1108 }
1109
1110 /* And link it to the new part. */
1111 prev->SetNext(t);
1112 prev = t;
1113 t = next;
1114 }
1115
1116 if (allowed_len < 0) return CommandCost(STR_ERROR_TRAIN_TOO_LONG);
1117 return CommandCost();
1118}
1119
1130 static CommandCost ValidateTrains(Train *original_dst, Train *dst, Train *original_src, Train *src, bool check_limit)
1131{
1132 /* Check whether we may actually construct the trains. */
1133 CommandCost ret = CheckTrainAttachment(src);
1134 if (ret.Failed()) return ret;
1135 ret = CheckTrainAttachment(dst);
1136 if (ret.Failed()) return ret;
1137
1138 /* Check whether we need to build a new train. */
1139 return check_limit ? CheckNewTrain(original_dst, dst, original_src, src) : CommandCost();
1140}
1141
1150 static void ArrangeTrains(Train **dst_head, Train *dst, Train **src_head, Train *src, bool move_chain)
1151{
1152 /* First determine the front of the two resulting trains */
1153 if (*src_head == *dst_head) {
1154 /* If we aren't moving part(s) to a new train, we are just moving the
1155 * front back and there is not destination head. */
1156 *dst_head = nullptr;
1157 } else if (*dst_head == nullptr) {
1158 /* If we are moving to a new train the head of the move train would become
1159 * the head of the new vehicle. */
1160 *dst_head = src;
1161 }
1162
1163 if (src == *src_head) {
1164 /* If we are moving the front of a train then we are, in effect, creating
1165 * a new head for the train. Point to that. Unless we are moving the whole
1166 * train in which case there is not 'source' train anymore.
1167 * In case we are a multiheaded part we want the complete thing to come
1168 * with us, so src->GetNextUnit(), however... when we are e.g. a wagon
1169 * that is followed by a rear multihead we do not want to include that. */
1170 *src_head = move_chain ? nullptr :
1171 (src->IsMultiheaded() ? src->GetNextUnit() : src->GetNextVehicle());
1172 }
1173
1174 /* Now it's just simply removing the part that we are going to move from the
1175 * source train and *if* the destination is a not a new train add the chain
1176 * at the destination location. */
1177 RemoveFromConsist(src, move_chain);
1178 if (*dst_head != src) InsertInConsist(dst, src);
1179
1180 /* Now normalise the dual heads, that is move the dual heads around in such
1181 * a way that the head and rear of a dual head are in the same train */
1182 NormaliseDualHeads(*src_head);
1183 NormaliseDualHeads(*dst_head);
1184}
1185
1191 static void NormaliseTrainHead(Train *head)
1192{
1193 /* Not much to do! */
1194 if (head == nullptr) return;
1195
1196 /* Tell the 'world' the train changed. */
1197 head->ConsistChanged(CCF_ARRANGE);
1198 UpdateTrainGroupID(head);
1199
1200 /* Not a front engine, i.e. a free wagon chain. No need to do more. */
1201 if (!head->IsFrontEngine()) return;
1202
1203 /* Update the refit button and window */
1204 InvalidateWindowData(WC_VEHICLE_REFIT, head->index, VIWD_CONSIST_CHANGED);
1205 SetWindowWidgetDirty(WC_VEHICLE_VIEW, head->index, WID_VV_REFIT);
1206
1207 /* If we don't have a unit number yet, set one. */
1208 if (head->unitnumber != 0) return;
1209 head->unitnumber = Company::Get(head->owner)->freeunits[head->type].UseID(GetFreeUnitNumber(VEH_TRAIN));
1210}
1211
1221 CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
1222{
1223 Train *src = Train::GetIfValid(src_veh);
1224 if (src == nullptr) return CMD_ERROR;
1225
1226 CommandCost ret = CheckOwnership(src->owner);
1227 if (ret.Failed()) return ret;
1228
1229 /* Do not allow moving crashed vehicles inside the depot, it is likely to cause asserts later */
1230 if (src->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1231
1232 /* if nothing is selected as destination, try and find a matching vehicle to drag to. */
1233 Train *dst;
1234 if (dest_veh == VehicleID::Invalid()) {
1235 dst = (src->IsEngine() || flags.Test(DoCommandFlag::AutoReplace)) ? nullptr : FindGoodVehiclePos(src);
1236 } else {
1237 dst = Train::GetIfValid(dest_veh);
1238 if (dst == nullptr) return CMD_ERROR;
1239
1240 ret = CheckOwnership(dst->owner);
1241 if (ret.Failed()) return ret;
1242
1243 /* Do not allow appending to crashed vehicles, too */
1244 if (dst->vehstatus.Test(VehState::Crashed)) return CMD_ERROR;
1245 }
1246
1247 /* if an articulated part is being handled, deal with its parent vehicle */
1248 src = src->GetFirstEnginePart();
1249 if (dst != nullptr) {
1250 dst = dst->GetFirstEnginePart();
1251 }
1252
1253 /* don't move the same vehicle.. */
1254 if (src == dst) return CommandCost();
1255
1256 /* locate the head of the two chains */
1257 Train *src_head = src->First();
1258 Train *dst_head;
1259 if (dst != nullptr) {
1260 dst_head = dst->First();
1261 if (dst_head->tile != src_head->tile) return CMD_ERROR;
1262 /* Now deal with articulated part of destination wagon */
1263 dst = dst->GetLastEnginePart();
1264 } else {
1265 dst_head = nullptr;
1266 }
1267
1268 if (src->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1269
1270 /* When moving all wagons, we can't have the same src_head and dst_head */
1271 if (move_chain && src_head == dst_head) return CommandCost();
1272
1273 /* When moving a multiheaded part to be place after itself, bail out. */
1274 if (!move_chain && dst != nullptr && dst->IsRearDualheaded() && src == dst->other_multiheaded_part) return CommandCost();
1275
1276 /* Check if all vehicles in the source train are stopped inside a depot. */
1277 if (!src_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1278
1279 /* Check if all vehicles in the destination train are stopped inside a depot. */
1280 if (dst_head != nullptr && !dst_head->IsStoppedInDepot()) return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
1281
1282 /* First make a backup of the order of the trains. That way we can do
1283 * whatever we want with the order and later on easily revert. */
1284 TrainList original_src;
1285 TrainList original_dst;
1286
1287 MakeTrainBackup(original_src, src_head);
1288 MakeTrainBackup(original_dst, dst_head);
1289
1290 /* Also make backup of the original heads as ArrangeTrains can change them.
1291 * For the destination head we do not care if it is the same as the source
1292 * head because in that case it's just a copy. */
1293 Train *original_src_head = src_head;
1294 Train *original_dst_head = (dst_head == src_head ? nullptr : dst_head);
1295
1296 /* We want this information from before the rearrangement, but execute this after the validation.
1297 * original_src_head can't be nullptr; src is by definition != nullptr, so src_head can't be nullptr as
1298 * src->GetFirst() always yields non-nullptr, so eventually original_src_head != nullptr as well. */
1299 bool original_src_head_front_engine = original_src_head->IsFrontEngine();
1300 bool original_dst_head_front_engine = original_dst_head != nullptr && original_dst_head->IsFrontEngine();
1301
1302 /* (Re)arrange the trains in the wanted arrangement. */
1303 ArrangeTrains(&dst_head, dst, &src_head, src, move_chain);
1304
1305 if (!flags.Test(DoCommandFlag::AutoReplace)) {
1306 /* If the autoreplace flag is set we do not need to test for the validity
1307 * because we are going to revert the train to its original state. As we
1308 * assume the original state was correct autoreplace can skip this. */
1309 ret = ValidateTrains(original_dst_head, dst_head, original_src_head, src_head, true);
1310 if (ret.Failed()) {
1311 /* Restore the train we had. */
1312 RestoreTrainBackup(original_src);
1313 RestoreTrainBackup(original_dst);
1314 return ret;
1315 }
1316 }
1317
1318 /* do it? */
1319 if (flags.Test(DoCommandFlag::Execute)) {
1320 /* Remove old heads from the statistics */
1321 if (original_src_head_front_engine) GroupStatistics::CountVehicle(original_src_head, -1);
1322 if (original_dst_head_front_engine) GroupStatistics::CountVehicle(original_dst_head, -1);
1323
1324 /* First normalise the sub types of the chains. */
1325 NormaliseSubtypes(src_head);
1326 NormaliseSubtypes(dst_head);
1327
1328 /* There are 14 different cases:
1329 * 1) front engine gets moved to a new train, it stays a front engine.
1330 * a) the 'next' part is a wagon that becomes a free wagon chain.
1331 * b) the 'next' part is an engine that becomes a front engine.
1332 * c) there is no 'next' part, nothing else happens
1333 * 2) front engine gets moved to another train, it is not a front engine anymore
1334 * a) the 'next' part is a wagon that becomes a free wagon chain.
1335 * b) the 'next' part is an engine that becomes a front engine.
1336 * c) there is no 'next' part, nothing else happens
1337 * 3) front engine gets moved to later in the current train, it is not a front engine anymore.
1338 * a) the 'next' part is a wagon that becomes a free wagon chain.
1339 * b) the 'next' part is an engine that becomes a front engine.
1340 * 4) free wagon gets moved
1341 * a) the 'next' part is a wagon that becomes a free wagon chain.
1342 * b) the 'next' part is an engine that becomes a front engine.
1343 * c) there is no 'next' part, nothing else happens
1344 * 5) non front engine gets moved and becomes a new train, nothing else happens
1345 * 6) non front engine gets moved within a train / to another train, nothing happens
1346 * 7) wagon gets moved, nothing happens
1347 */
1348 if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) {
1349 /* Cases #2 and #3: the front engine gets trashed. */
1350 CloseWindowById(WC_VEHICLE_VIEW, src->index);
1351 CloseWindowById(WC_VEHICLE_ORDERS, src->index);
1352 CloseWindowById(WC_VEHICLE_REFIT, src->index);
1353 CloseWindowById(WC_VEHICLE_DETAILS, src->index);
1354 CloseWindowById(WC_VEHICLE_TIMETABLE, src->index);
1355 DeleteNewGRFInspectWindow(GSF_TRAINS, src->index);
1356 SetWindowDirty(WC_COMPANY, _current_company);
1357
1358 if (src_head != nullptr && src_head->IsFrontEngine()) {
1359 /* Cases #?b: Transfer order, unit number and other stuff
1360 * to the new front engine. */
1361 src_head->orders = src->orders;
1362 if (src_head->orders != nullptr) src_head->AddToShared(src);
1363 src_head->CopyVehicleConfigAndStatistics(src);
1364 }
1365 /* Remove stuff not valid anymore for non-front engines. */
1366 DeleteVehicleOrders(src);
1367 src->ReleaseUnitNumber();
1368 src->name.clear();
1369 }
1370
1371 /* We weren't a front engine but are becoming one. So
1372 * we should be put in the default group. */
1373 if (original_src_head != src && dst_head == src) {
1374 SetTrainGroupID(src, DEFAULT_GROUP);
1375 SetWindowDirty(WC_COMPANY, _current_company);
1376 }
1377
1378 /* Handle 'new engine' part of cases #1b, #2b, #3b, #4b and #5 in NormaliseTrainHead. */
1379 NormaliseTrainHead(src_head);
1380 NormaliseTrainHead(dst_head);
1381
1382 /* Add new heads to statistics.
1383 * This should be done after NormaliseTrainHead due to engine total limit checks in GetFreeUnitNumber. */
1384 if (src_head != nullptr && src_head->IsFrontEngine()) GroupStatistics::CountVehicle(src_head, 1);
1385 if (dst_head != nullptr && dst_head->IsFrontEngine()) GroupStatistics::CountVehicle(dst_head, 1);
1386
1387 if (!flags.Test(DoCommandFlag::NoCargoCapacityCheck)) {
1388 CheckCargoCapacity(src_head);
1389 CheckCargoCapacity(dst_head);
1390 }
1391
1392 if (src_head != nullptr) src_head->First()->MarkDirty();
1393 if (dst_head != nullptr) dst_head->First()->MarkDirty();
1394
1395 /* We are undoubtedly changing something in the depot and train list. */
1396 InvalidateWindowData(WC_VEHICLE_DEPOT, src->tile);
1397 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1398 } else {
1399 /* We don't want to execute what we're just tried. */
1400 RestoreTrainBackup(original_src);
1401 RestoreTrainBackup(original_dst);
1402 }
1403
1404 return CommandCost();
1405}
1406
1419 CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
1420{
1421 Train *v = Train::From(t)->GetFirstEnginePart();
1422 Train *first = v->First();
1423
1424 if (v->IsRearDualheaded()) return CommandCost(STR_ERROR_REAR_ENGINE_FOLLOW_FRONT);
1425
1426 /* First make a backup of the order of the train. That way we can do
1427 * whatever we want with the order and later on easily revert. */
1428 TrainList original;
1429 MakeTrainBackup(original, first);
1430
1431 /* We need to keep track of the new head and the head of what we're going to sell. */
1432 Train *new_head = first;
1433 Train *sell_head = nullptr;
1434
1435 /* Split the train in the wanted way. */
1436 ArrangeTrains(&sell_head, nullptr, &new_head, v, sell_chain);
1437
1438 /* We don't need to validate the second train; it's going to be sold. */
1439 CommandCost ret = ValidateTrains(nullptr, nullptr, first, new_head, !flags.Test(DoCommandFlag::AutoReplace));
1440 if (ret.Failed()) {
1441 /* Restore the train we had. */
1442 RestoreTrainBackup(original);
1443 return ret;
1444 }
1445
1446 if (first->orders == nullptr && !OrderList::CanAllocateItem()) {
1447 /* Restore the train we had. */
1448 RestoreTrainBackup(original);
1449 return CommandCost(STR_ERROR_NO_MORE_SPACE_FOR_ORDERS);
1450 }
1451
1452 CommandCost cost(EXPENSES_NEW_VEHICLES);
1453 for (Train *part = sell_head; part != nullptr; part = part->Next()) cost.AddCost(-part->value);
1454
1455 /* do it? */
1456 if (flags.Test(DoCommandFlag::Execute)) {
1457 /* First normalise the sub types of the chain. */
1458 NormaliseSubtypes(new_head);
1459
1460 if (v == first && !sell_chain && new_head != nullptr && new_head->IsFrontEngine()) {
1461 if (v->IsEngine()) {
1462 /* We are selling the front engine. In this case we want to
1463 * 'give' the order, unit number and such to the new head. */
1464 new_head->orders = first->orders;
1465 new_head->AddToShared(first);
1466 DeleteVehicleOrders(first);
1467
1468 /* Copy other important data from the front engine */
1469 new_head->CopyVehicleConfigAndStatistics(first);
1470 }
1471 GroupStatistics::CountVehicle(new_head, 1); // after copying over the profit, if required
1472 } else if (v->IsPrimaryVehicle() && backup_order) {
1473 OrderBackup::Backup(v, user);
1474 }
1475
1476 /* We need to update the information about the train. */
1477 NormaliseTrainHead(new_head);
1478
1479 /* We are undoubtedly changing something in the depot and train list. */
1480 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1481 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
1482
1483 /* Actually delete the sold 'goods' */
1484 delete sell_head;
1485 } else {
1486 /* We don't want to execute what we're just tried. */
1487 RestoreTrainBackup(original);
1488 }
1489
1490 return cost;
1491}
1492
1493 void Train::UpdateDeltaXY()
1494{
1495 /* Set common defaults. */
1496 this->bounds = {{-1, -1, 0}, {3, 3, 6}, {}};
1497
1498 /* Set if flipped and engine is NOT flagged with custom flip handling. */
1499 int flipped = this->flags.Test(VehicleRailFlag::Flipped) && !EngInfo(this->engine_type)->misc_flags.Test(EngineMiscFlag::RailFlips);
1500 /* If flipped and vehicle length is odd, we need to adjust the bounding box offset slightly. */
1501 int flip_offs = flipped && (this->gcache.cached_veh_length & 1);
1502
1503 Direction dir = this->direction;
1504 if (flipped) dir = ReverseDir(dir);
1505
1506 if (!IsDiagonalDirection(dir)) {
1507 static const Point _sign_table[] = {
1508 /* x, y */
1509 {-1, -1}, // DIR_N
1510 {-1, 1}, // DIR_E
1511 { 1, 1}, // DIR_S
1512 { 1, -1}, // DIR_W
1513 };
1514
1515 int half_shorten = (VEHICLE_LENGTH - this->gcache.cached_veh_length + flipped) / 2;
1516
1517 /* For all straight directions, move the bound box to the centre of the vehicle, but keep the size. */
1518 this->bounds.offset.x -= half_shorten * _sign_table[DirToDiagDir(dir)].x;
1519 this->bounds.offset.y -= half_shorten * _sign_table[DirToDiagDir(dir)].y;
1520 } else {
1521 switch (dir) {
1522 /* Shorten southern corner of the bounding box according the vehicle length
1523 * and center the bounding box on the vehicle. */
1524 case DIR_NE:
1525 this->bounds.origin.x = -(this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1526 this->bounds.extent.x = this->gcache.cached_veh_length;
1527 this->bounds.offset.x = 1;
1528 break;
1529
1530 case DIR_NW:
1531 this->bounds.origin.y = -(this->gcache.cached_veh_length + 1) / 2 + flip_offs;
1532 this->bounds.extent.y = this->gcache.cached_veh_length;
1533 this->bounds.offset.y = 1;
1534 break;
1535
1536 /* Move northern corner of the bounding box down according to vehicle length
1537 * and center the bounding box on the vehicle. */
1538 case DIR_SW:
1539 this->bounds.origin.x = -(this->gcache.cached_veh_length) / 2 - flip_offs;
1540 this->bounds.extent.x = this->gcache.cached_veh_length;
1541 this->bounds.offset.x = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
1542 break;
1543
1544 case DIR_SE:
1545 this->bounds.origin.y = -(this->gcache.cached_veh_length) / 2 - flip_offs;
1546 this->bounds.extent.y = this->gcache.cached_veh_length;
1547 this->bounds.offset.y = 1 - (VEHICLE_LENGTH - this->gcache.cached_veh_length);
1548 break;
1549
1550 default:
1551 NOT_REACHED();
1552 }
1553 }
1554}
1555
1560 static void MarkTrainAsStuck(Train *v)
1561{
1562 if (!v->flags.Test(VehicleRailFlag::Stuck)) {
1563 /* It is the first time the problem occurred, set the "train stuck" flag. */
1564 v->flags.Set(VehicleRailFlag::Stuck);
1565
1566 v->wait_counter = 0;
1567
1568 /* Stop train */
1569 v->cur_speed = 0;
1570 v->subspeed = 0;
1571 v->SetLastSpeed();
1572
1573 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1574 }
1575}
1576
1584 static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
1585{
1586 uint16_t flag1 = *swap_flag1;
1587 uint16_t flag2 = *swap_flag2;
1588
1589 /* Clear the flags */
1590 ClrBit(*swap_flag1, GVF_GOINGUP_BIT);
1591 ClrBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1592 ClrBit(*swap_flag2, GVF_GOINGUP_BIT);
1593 ClrBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1594
1595 /* Reverse the rail-flags (if needed) */
1596 if (HasBit(flag1, GVF_GOINGUP_BIT)) {
1597 SetBit(*swap_flag2, GVF_GOINGDOWN_BIT);
1598 } else if (HasBit(flag1, GVF_GOINGDOWN_BIT)) {
1599 SetBit(*swap_flag2, GVF_GOINGUP_BIT);
1600 }
1601 if (HasBit(flag2, GVF_GOINGUP_BIT)) {
1602 SetBit(*swap_flag1, GVF_GOINGDOWN_BIT);
1603 } else if (HasBit(flag2, GVF_GOINGDOWN_BIT)) {
1604 SetBit(*swap_flag1, GVF_GOINGUP_BIT);
1605 }
1606}
1607
1612 static void UpdateStatusAfterSwap(Train *v)
1613{
1614 /* Reverse the direction. */
1615 if (v->track != TRACK_BIT_DEPOT) v->direction = ReverseDir(v->direction);
1616
1617 /* Call the proper EnterTile function unless we are in a wormhole. */
1618 if (v->track != TRACK_BIT_WORMHOLE) {
1619 VehicleEnterTile(v, v->tile, v->x_pos, v->y_pos);
1620 } else {
1621 /* VehicleEnter_TunnelBridge() sets TRACK_BIT_WORMHOLE when the vehicle
1622 * is on the last bit of the bridge head (frame == TILE_SIZE - 1).
1623 * If we were swapped with such a vehicle, we have set TRACK_BIT_WORMHOLE,
1624 * when we shouldn't have. Check if this is the case. */
1625 TileIndex vt = TileVirtXY(v->x_pos, v->y_pos);
1626 if (IsTileType(vt, MP_TUNNELBRIDGE)) {
1627 VehicleEnterTile(v, vt, v->x_pos, v->y_pos);
1628 if (v->track != TRACK_BIT_WORMHOLE && IsBridgeTile(v->tile)) {
1629 /* We have just left the wormhole, possibly set the
1630 * "goingdown" bit. UpdateInclination() can be used
1631 * because we are at the border of the tile. */
1632 v->UpdatePosition();
1633 v->UpdateInclination(true, true);
1634 return;
1635 }
1636 }
1637 }
1638
1639 v->UpdatePosition();
1640 v->UpdateViewport(true, true);
1641}
1642
1649 void ReverseTrainSwapVeh(Train *v, int l, int r)
1650{
1651 Train *a, *b;
1652
1653 /* locate vehicles to swap */
1654 for (a = v; l != 0; l--) a = a->Next();
1655 for (b = v; r != 0; r--) b = b->Next();
1656
1657 if (a != b) {
1658 /* swap the hidden bits */
1659 {
1660 bool a_hidden = a->vehstatus.Test(VehState::Hidden);
1661 bool b_hidden = b->vehstatus.Test(VehState::Hidden);
1662 b->vehstatus.Set(VehState::Hidden, a_hidden);
1663 a->vehstatus.Set(VehState::Hidden, b_hidden);
1664 }
1665
1666 std::swap(a->track, b->track);
1667 std::swap(a->direction, b->direction);
1668 std::swap(a->x_pos, b->x_pos);
1669 std::swap(a->y_pos, b->y_pos);
1670 std::swap(a->tile, b->tile);
1671 std::swap(a->z_pos, b->z_pos);
1672
1673 SwapTrainFlags(&a->gv_flags, &b->gv_flags);
1674
1675 UpdateStatusAfterSwap(a);
1676 UpdateStatusAfterSwap(b);
1677 } else {
1678 /* Swap GVF_GOINGUP_BIT/GVF_GOINGDOWN_BIT.
1679 * This is a little bit redundant way, a->gv_flags will
1680 * be (re)set twice, but it reduces code duplication */
1681 SwapTrainFlags(&a->gv_flags, &a->gv_flags);
1682 UpdateStatusAfterSwap(a);
1683 }
1684}
1685
1691 static bool IsTrain(const Vehicle *v)
1692{
1693 return v->type == VEH_TRAIN;
1694}
1695
1702 bool TrainOnCrossing(TileIndex tile)
1703{
1704 assert(IsLevelCrossingTile(tile));
1705
1706 return HasVehicleOnTile(tile, IsTrain);
1707}
1708
1715 static bool TrainApproachingCrossingEnum(const Vehicle *v, TileIndex tile)
1716{
1717 if (v->type != VEH_TRAIN || v->vehstatus.Test(VehState::Crashed)) return false;
1718
1719 const Train *t = Train::From(v);
1720 if (!t->IsFrontEngine()) return false;
1721
1722 return TrainApproachingCrossingTile(t) == tile;
1723}
1724
1725
1732 static bool TrainApproachingCrossing(TileIndex tile)
1733{
1734 assert(IsLevelCrossingTile(tile));
1735
1736 DiagDirection dir = AxisToDiagDir(GetCrossingRailAxis(tile));
1737 TileIndex tile_from = tile + TileOffsByDiagDir(dir);
1738
1739 if (HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1740 return TrainApproachingCrossingEnum(v, tile);
1741 })) return true;
1742
1743 dir = ReverseDiagDir(dir);
1744 tile_from = tile + TileOffsByDiagDir(dir);
1745
1746 return HasVehicleOnTile(tile_from, [&](const Vehicle *v) {
1747 return TrainApproachingCrossingEnum(v, tile);
1748 });
1749}
1750
1756 static inline bool CheckLevelCrossing(TileIndex tile)
1757{
1758 /* reserved || train on crossing || train approaching crossing */
1759 return HasCrossingReservation(tile) || TrainOnCrossing(tile) || TrainApproachingCrossing(tile);
1760}
1761
1769 static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
1770{
1771 assert(IsLevelCrossingTile(tile));
1772 bool set_barred;
1773
1774 /* We force the crossing to be barred when an adjacent crossing is barred, otherwise let it decide for itself. */
1775 set_barred = force_barred || CheckLevelCrossing(tile);
1776
1777 /* The state has changed */
1778 if (set_barred != IsCrossingBarred(tile)) {
1779 if (set_barred && sound && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, tile);
1780 SetCrossingBarred(tile, set_barred);
1781 MarkTileDirtyByTile(tile);
1782 }
1783}
1784
1791 void UpdateLevelCrossing(TileIndex tile, bool sound, bool force_bar)
1792{
1793 if (!IsLevelCrossingTile(tile)) return;
1794
1795 bool forced_state = force_bar;
1796
1797 const Axis axis = GetCrossingRoadAxis(tile);
1798 const DiagDirection dir1 = AxisToDiagDir(axis);
1799 const DiagDirection dir2 = ReverseDiagDir(dir1);
1800
1801 /* Check if an adjacent crossing is barred. */
1802 for (DiagDirection dir : { dir1, dir2 }) {
1803 for (TileIndex t = tile; !forced_state && t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1804 forced_state |= CheckLevelCrossing(t);
1805 }
1806 }
1807
1808 /* Now that we know whether all tiles in this crossing should be barred or open,
1809 * we need to update those tiles. We start with the tile itself, then look along the road axis. */
1810 UpdateLevelCrossingTile(tile, sound, forced_state);
1811 for (DiagDirection dir : { dir1, dir2 }) {
1812 for (TileIndex t = TileAddByDiagDir(tile, dir); t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == axis; t = TileAddByDiagDir(t, dir)) {
1813 UpdateLevelCrossingTile(t, sound, forced_state);
1814 }
1815 }
1816}
1817
1823 void MarkDirtyAdjacentLevelCrossingTiles(TileIndex tile, Axis road_axis)
1824{
1825 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1826 const DiagDirection dir2 = ReverseDiagDir(dir1);
1827 for (DiagDirection dir : { dir1, dir2 }) {
1828 const TileIndex t = TileAddByDiagDir(tile, dir);
1829 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1830 MarkTileDirtyByTile(t);
1831 }
1832 }
1833}
1834
1840 void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
1841{
1842 const DiagDirection dir1 = AxisToDiagDir(road_axis);
1843 const DiagDirection dir2 = ReverseDiagDir(dir1);
1844 for (DiagDirection dir : { dir1, dir2 }) {
1845 const TileIndexDiff diff = TileOffsByDiagDir(dir);
1846 bool occupied = false;
1847 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1848 occupied |= CheckLevelCrossing(t);
1849 }
1850 if (occupied) {
1851 /* Mark the immediately adjacent tile dirty */
1852 const TileIndex t = tile + diff;
1853 if (t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis) {
1854 MarkTileDirtyByTile(t);
1855 }
1856 } else {
1857 /* Unbar the crossing tiles in this direction as necessary */
1858 for (TileIndex t = tile + diff; t < Map::Size() && IsLevelCrossingTile(t) && GetCrossingRoadAxis(t) == road_axis; t += diff) {
1859 if (IsCrossingBarred(t)) {
1860 /* The crossing tile is barred, unbar it and continue to check the next tile */
1861 SetCrossingBarred(t, false);
1862 MarkTileDirtyByTile(t);
1863 } else {
1864 /* The crossing tile is already unbarred, mark the tile dirty and stop checking */
1865 MarkTileDirtyByTile(t);
1866 break;
1867 }
1868 }
1869 }
1870 }
1871}
1872
1878 static inline void MaybeBarCrossingWithSound(TileIndex tile)
1879{
1880 if (!IsCrossingBarred(tile)) {
1881 SetCrossingReservation(tile, true);
1882 UpdateLevelCrossing(tile, true);
1883 }
1884}
1885
1886
1892 static void AdvanceWagonsBeforeSwap(Train *v)
1893{
1894 Train *base = v;
1895 Train *first = base; // first vehicle to move
1896 Train *last = v->Last(); // last vehicle to move
1897 uint length = CountVehiclesInChain(v);
1898
1899 while (length > 2) {
1900 last = last->Previous();
1901 first = first->Next();
1902
1903 int differential = base->CalcNextVehicleOffset() - last->CalcNextVehicleOffset();
1904
1905 /* do not update images now
1906 * negative differential will be handled in AdvanceWagonsAfterSwap() */
1907 for (int i = 0; i < differential; i++) TrainController(first, last->Next());
1908
1909 base = first; // == base->Next()
1910 length -= 2;
1911 }
1912}
1913
1914
1920 static void AdvanceWagonsAfterSwap(Train *v)
1921{
1922 /* first of all, fix the situation when the train was entering a depot */
1923 Train *dep = v; // last vehicle in front of just left depot
1924 while (dep->Next() != nullptr && (dep->track == TRACK_BIT_DEPOT || dep->Next()->track != TRACK_BIT_DEPOT)) {
1925 dep = dep->Next(); // find first vehicle outside of a depot, with next vehicle inside a depot
1926 }
1927
1928 Train *leave = dep->Next(); // first vehicle in a depot we are leaving now
1929
1930 if (leave != nullptr) {
1931 /* 'pull' next wagon out of the depot, so we won't miss it (it could stay in depot forever) */
1932 int d = TicksToLeaveDepot(dep);
1933
1934 if (d <= 0) {
1935 leave->vehstatus.Reset(VehState::Hidden); // move it out of the depot
1936 leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
1937 for (int i = 0; i >= d; i--) TrainController(leave, nullptr); // maybe move it, and maybe let another wagon leave
1938 }
1939 } else {
1940 dep = nullptr; // no vehicle in a depot, so no vehicle leaving a depot
1941 }
1942
1943 Train *base = v;
1944 Train *first = base; // first vehicle to move
1945 Train *last = v->Last(); // last vehicle to move
1946 uint length = CountVehiclesInChain(v);
1947
1948 /* We have to make sure all wagons that leave a depot because of train reversing are moved correctly
1949 * they have already correct spacing, so we have to make sure they are moved how they should */
1950 bool nomove = (dep == nullptr); // If there is no vehicle leaving a depot, limit the number of wagons moved immediately.
1951
1952 while (length > 2) {
1953 /* we reached vehicle (originally) in front of a depot, stop now
1954 * (we would move wagons that are already moved with new wagon length). */
1955 if (base == dep) break;
1956
1957 /* the last wagon was that one leaving a depot, so do not move it anymore */
1958 if (last == dep) nomove = true;
1959
1960 last = last->Previous();
1961 first = first->Next();
1962
1963 int differential = last->CalcNextVehicleOffset() - base->CalcNextVehicleOffset();
1964
1965 /* do not update images now */
1966 for (int i = 0; i < differential; i++) TrainController(first, (nomove ? last->Next() : nullptr));
1967
1968 base = first; // == base->Next()
1969 length -= 2;
1970 }
1971}
1972
1973static bool IsWholeTrainInsideDepot(const Train *v)
1974{
1975 for (const Train *u = v; u != nullptr; u = u->Next()) {
1976 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
1977 }
1978 return true;
1979}
1980
1985 void ReverseTrainDirection(Train *v)
1986{
1987 if (IsRailDepotTile(v->tile)) {
1988 if (IsWholeTrainInsideDepot(v)) return;
1989 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1990 }
1991
1992 /* Clear path reservation in front if train is not stuck. */
1993 if (!v->flags.Test(VehicleRailFlag::Stuck)) FreeTrainTrackReservation(v);
1994
1995 /* Check if we were approaching a rail/road-crossing */
1996 TileIndex crossing = TrainApproachingCrossingTile(v);
1997
1998 /* count number of vehicles */
1999 int r = CountVehiclesInChain(v) - 1; // number of vehicles - 1
2000
2001 AdvanceWagonsBeforeSwap(v);
2002
2003 /* swap start<>end, start+1<>end-1, ... */
2004 int l = 0;
2005 do {
2006 ReverseTrainSwapVeh(v, l++, r--);
2007 } while (l <= r);
2008
2009 AdvanceWagonsAfterSwap(v);
2010
2011 if (IsRailDepotTile(v->tile)) {
2012 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2013 }
2014
2015 v->flags.Flip(VehicleRailFlag::Reversed);
2016 v->flags.Reset(VehicleRailFlag::Reversing);
2017
2018 /* recalculate cached data */
2019 v->ConsistChanged(CCF_TRACK);
2020
2021 /* update all images */
2022 for (Train *u = v; u != nullptr; u = u->Next()) u->UpdateViewport(false, false);
2023
2024 /* update crossing we were approaching */
2025 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
2026
2027 /* maybe we are approaching crossing now, after reversal */
2028 crossing = TrainApproachingCrossingTile(v);
2029 if (crossing != INVALID_TILE) MaybeBarCrossingWithSound(crossing);
2030
2031 /* If we are inside a depot after reversing, don't bother with path reserving. */
2032 if (v->track == TRACK_BIT_DEPOT) {
2033 /* Can't be stuck here as inside a depot is always a safe tile. */
2034 if (v->flags.Test(VehicleRailFlag::Stuck)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2035 v->flags.Reset(VehicleRailFlag::Stuck);
2036 return;
2037 }
2038
2039 /* VehicleExitDir does not always produce the desired dir for depots and
2040 * tunnels/bridges that is needed for UpdateSignalsOnSegment. */
2041 DiagDirection dir = VehicleExitDir(v->direction, v->track);
2042 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
2043
2044 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
2045 /* If we are currently on a tile with conventional signals, we can't treat the
2046 * current tile as a safe tile or we would enter a PBS block without a reservation. */
2047 bool first_tile_okay = !(IsTileType(v->tile, MP_RAILWAY) &&
2048 HasSignalOnTrackdir(v->tile, v->GetVehicleTrackdir()) &&
2049 !IsPbsSignal(GetSignalType(v->tile, FindFirstTrack(v->track))));
2050
2051 /* If we are on a depot tile facing outwards, do not treat the current tile as safe. */
2052 if (IsRailDepotTile(v->tile) && TrackdirToExitdir(v->GetVehicleTrackdir()) == GetRailDepotDirection(v->tile)) first_tile_okay = false;
2053
2054 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
2055 if (TryPathReserve(v, false, first_tile_okay)) {
2056 /* Do a look-ahead now in case our current tile was already a safe tile. */
2057 CheckNextTrainTile(v);
2058 } else if (v->current_order.GetType() != OT_LOADING) {
2059 /* Do not wait for a way out when we're still loading */
2060 MarkTrainAsStuck(v);
2061 }
2062 } else if (v->flags.Test(VehicleRailFlag::Stuck)) {
2063 /* A train not inside a PBS block can't be stuck. */
2064 v->flags.Reset(VehicleRailFlag::Stuck);
2065 v->wait_counter = 0;
2066 }
2067}
2068
2076 CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
2077{
2078 Train *v = Train::GetIfValid(veh_id);
2079 if (v == nullptr) return CMD_ERROR;
2080
2081 CommandCost ret = CheckOwnership(v->owner);
2082 if (ret.Failed()) return ret;
2083
2084 if (reverse_single_veh) {
2085 /* turn a single unit around */
2086
2087 if (v->IsMultiheaded() || EngInfo(v->engine_type)->callback_mask.Test(VehicleCallbackMask::ArticEngine)) {
2088 return CommandCost(STR_ERROR_CAN_T_REVERSE_DIRECTION_RAIL_VEHICLE_MULTIPLE_UNITS);
2089 }
2090
2091 Train *front = v->First();
2092 /* make sure the vehicle is stopped in the depot */
2093 if (!front->IsStoppedInDepot()) {
2094 return CommandCost(STR_ERROR_TRAINS_CAN_ONLY_BE_ALTERED_INSIDE_A_DEPOT);
2095 }
2096
2097 if (flags.Test(DoCommandFlag::Execute)) {
2098 v->flags.Flip(VehicleRailFlag::Flipped);
2099
2100 front->ConsistChanged(CCF_ARRANGE);
2101 SetWindowDirty(WC_VEHICLE_DEPOT, front->tile);
2102 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2103 SetWindowDirty(WC_VEHICLE_VIEW, front->index);
2104 SetWindowClassesDirty(WC_TRAINS_LIST);
2105 }
2106 } else {
2107 /* turn the whole train around */
2108 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
2109 if (v->vehstatus.Test(VehState::Crashed) || v->breakdown_ctr != 0) return CMD_ERROR;
2110
2111 if (flags.Test(DoCommandFlag::Execute)) {
2112 /* Properly leave the station if we are loading and won't be loading anymore */
2113 if (v->current_order.IsType(OT_LOADING)) {
2114 const Vehicle *last = v;
2115 while (last->Next() != nullptr) last = last->Next();
2116
2117 /* not a station || different station --> leave the station */
2118 if (!IsTileType(last->tile, MP_STATION) || GetStationIndex(last->tile) != GetStationIndex(v->tile)) {
2119 v->LeaveStation();
2120 }
2121 }
2122
2123 /* We cancel any 'skip signal at dangers' here */
2124 v->force_proceed = TFP_NONE;
2125 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
2126
2127 if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && v->cur_speed != 0) {
2128 v->flags.Flip(VehicleRailFlag::Reversing);
2129 } else {
2130 v->cur_speed = 0;
2131 v->SetLastSpeed();
2132 HideFillingPercent(&v->fill_percent_te_id);
2133 ReverseTrainDirection(v);
2134 }
2135
2136 /* Unbunching data is no longer valid. */
2137 v->ResetDepotUnbunching();
2138 }
2139 }
2140 return CommandCost();
2141}
2142
2153 static TrainForceProceeding DetermineNextTrainForceProceeding(const Train *t)
2154{
2155 if (t->vehstatus.Test(VehState::Crashed) || t->force_proceed == TFP_SIGNAL) return TFP_NONE;
2156 if (!t->flags.Test(VehicleRailFlag::Stuck)) return t->IsChainInDepot() ? TFP_STUCK : TFP_SIGNAL;
2157
2158 TileIndex next_tile = TileAddByDiagDir(t->tile, TrackdirToExitdir(t->GetVehicleTrackdir()));
2159 if (next_tile == INVALID_TILE || !IsTileType(next_tile, MP_RAILWAY) || !HasSignals(next_tile)) return TFP_STUCK;
2160 TrackBits new_tracks = DiagdirReachesTracks(TrackdirToExitdir(t->GetVehicleTrackdir())) & GetTrackBits(next_tile);
2161 return new_tracks != TRACK_BIT_NONE && HasSignalOnTrack(next_tile, FindFirstTrack(new_tracks)) ? TFP_SIGNAL : TFP_STUCK;
2162}
2163
2170 CommandCost CmdForceTrainProceed(DoCommandFlags flags, VehicleID veh_id)
2171{
2172 Train *t = Train::GetIfValid(veh_id);
2173 if (t == nullptr) return CMD_ERROR;
2174
2175 if (!t->IsPrimaryVehicle()) return CMD_ERROR;
2176
2177 CommandCost ret = CheckOwnership(t->owner);
2178 if (ret.Failed()) return ret;
2179
2180
2181 if (flags.Test(DoCommandFlag::Execute)) {
2182 t->force_proceed = DetermineNextTrainForceProceeding(t);
2183 SetWindowDirty(WC_VEHICLE_VIEW, t->index);
2184
2185 /* Unbunching data is no longer valid. */
2186 t->ResetDepotUnbunching();
2187 }
2188
2189 return CommandCost();
2190}
2191
2199 static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
2200{
2201 assert(!v->vehstatus.Test(VehState::Crashed));
2202
2203 return YapfTrainFindNearestDepot(v, max_distance);
2204}
2205
2206 ClosestDepot Train::FindClosestDepot()
2207{
2208 FindDepotData tfdd = FindClosestTrainDepot(this, 0);
2209 if (tfdd.best_length == UINT_MAX) return ClosestDepot();
2210
2211 return ClosestDepot(tfdd.tile, GetDepotIndex(tfdd.tile), tfdd.reverse);
2212}
2213
2215 void Train::PlayLeaveStationSound(bool force) const
2216{
2217 static const SoundFx sfx[] = {
2218 SND_04_DEPARTURE_STEAM,
2219 SND_0A_DEPARTURE_TRAIN,
2220 SND_0A_DEPARTURE_TRAIN,
2221 SND_47_DEPARTURE_MONORAIL,
2222 SND_41_DEPARTURE_MAGLEV
2223 };
2224
2225 if (PlayVehicleSound(this, VSE_START, force)) return;
2226
2227 SndPlayVehicleFx(sfx[RailVehInfo(this->engine_type)->engclass], this);
2228}
2229
2234 static void CheckNextTrainTile(Train *v)
2235{
2236 /* Don't do any look-ahead if path_backoff_interval is 255. */
2237 if (_settings_game.pf.path_backoff_interval == 255) return;
2238
2239 /* Exit if we are inside a depot. */
2240 if (v->track == TRACK_BIT_DEPOT) return;
2241
2242 switch (v->current_order.GetType()) {
2243 /* Exit if we reached our destination depot. */
2244 case OT_GOTO_DEPOT:
2245 if (v->tile == v->dest_tile) return;
2246 break;
2247
2248 case OT_GOTO_WAYPOINT:
2249 /* If we reached our waypoint, make sure we see that. */
2250 if (IsRailWaypointTile(v->tile) && GetStationIndex(v->tile) == v->current_order.GetDestination()) ProcessOrders(v);
2251 break;
2252
2253 case OT_NOTHING:
2254 case OT_LEAVESTATION:
2255 case OT_LOADING:
2256 /* Exit if the current order doesn't have a destination, but the train has orders. */
2257 if (v->GetNumOrders() > 0) return;
2258 break;
2259
2260 default:
2261 break;
2262 }
2263 /* Exit if we are on a station tile and are going to stop. */
2264 if (IsRailStationTile(v->tile) && v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile))) return;
2265
2266 Trackdir td = v->GetVehicleTrackdir();
2267
2268 /* On a tile with a red non-pbs signal, don't look ahead. */
2269 if (IsTileType(v->tile, MP_RAILWAY) && HasSignalOnTrackdir(v->tile, td) &&
2270 !IsPbsSignal(GetSignalType(v->tile, TrackdirToTrack(td))) &&
2271 GetSignalStateByTrackdir(v->tile, td) == SIGNAL_STATE_RED) return;
2272
2273 CFollowTrackRail ft(v);
2274 if (!ft.Follow(v->tile, td)) return;
2275
2276 if (!HasReservedTracks(ft.new_tile, TrackdirBitsToTrackBits(ft.new_td_bits))) {
2277 /* Next tile is not reserved. */
2278 if (KillFirstBit(ft.new_td_bits) == TRACKDIR_BIT_NONE) {
2279 if (HasPbsSignalOnTrackdir(ft.new_tile, FindFirstTrackdir(ft.new_td_bits))) {
2280 /* If the next tile is a PBS signal, try to make a reservation. */
2281 TrackBits tracks = TrackdirBitsToTrackBits(ft.new_td_bits);
2282 if (Rail90DegTurnDisallowed(GetTileRailType(ft.old_tile), GetTileRailType(ft.new_tile))) {
2283 tracks &= ~TrackCrossesTracks(TrackdirToTrack(ft.old_td));
2284 }
2285 ChooseTrainTrack(v, ft.new_tile, ft.exitdir, tracks, false, nullptr, false);
2286 }
2287 }
2288 }
2289}
2290
2296 static bool CheckTrainStayInDepot(Train *v)
2297{
2298 /* bail out if not all wagons are in the same depot or not in a depot at all */
2299 for (const Train *u = v; u != nullptr; u = u->Next()) {
2300 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return false;
2301 }
2302
2303 /* if the train got no power, then keep it in the depot */
2304 if (v->gcache.cached_power == 0) {
2305 v->vehstatus.Set(VehState::Stopped);
2306 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
2307 return true;
2308 }
2309
2310 /* Check if we should wait here for unbunching. */
2311 if (v->IsWaitingForUnbunching()) return true;
2312
2313 SigSegState seg_state;
2314
2315 if (v->force_proceed == TFP_NONE) {
2316 /* force proceed was not pressed */
2317 if (++v->wait_counter < 37) {
2318 SetWindowClassesDirty(WC_TRAINS_LIST);
2319 return true;
2320 }
2321
2322 v->wait_counter = 0;
2323
2324 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2325 if (seg_state == SIGSEG_FULL || HasDepotReservation(v->tile)) {
2326 /* Full and no PBS signal in block or depot reserved, can't exit. */
2327 SetWindowClassesDirty(WC_TRAINS_LIST);
2328 return true;
2329 }
2330 } else {
2331 seg_state = _settings_game.pf.reserve_paths ? SIGSEG_PBS : UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2332 }
2333
2334 /* We are leaving a depot, but have to go to the exact same one; re-enter. */
2335 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
2336 /* Service when depot has no reservation. */
2337 if (!HasDepotReservation(v->tile)) VehicleEnterDepot(v);
2338 return true;
2339 }
2340
2341 /* Only leave when we can reserve a path to our destination. */
2342 if (seg_state == SIGSEG_PBS && !TryPathReserve(v) && v->force_proceed == TFP_NONE) {
2343 /* No path and no force proceed. */
2344 SetWindowClassesDirty(WC_TRAINS_LIST);
2345 MarkTrainAsStuck(v);
2346 return true;
2347 }
2348
2349 SetDepotReservation(v->tile, true);
2350 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2351
2352 VehicleServiceInDepot(v);
2353 v->LeaveUnbunchingDepot();
2354 v->PlayLeaveStationSound();
2355 SetWindowClassesDirty(WC_TRAINS_LIST);
2356
2357 v->track = TRACK_BIT_X;
2358 if (v->direction & 2) v->track = TRACK_BIT_Y;
2359
2360 v->vehstatus.Reset(VehState::Hidden);
2361 v->cur_speed = 0;
2362
2363 v->UpdateViewport(true, true);
2364 v->UpdatePosition();
2365 UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
2366 v->UpdateAcceleration();
2367 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
2368
2369 return false;
2370}
2371
2378 static void ClearPathReservation(const Train *v, TileIndex tile, Trackdir track_dir)
2379{
2380 DiagDirection dir = TrackdirToExitdir(track_dir);
2381
2382 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
2383 /* Are we just leaving a tunnel/bridge? */
2384 if (GetTunnelBridgeDirection(tile) == ReverseDiagDir(dir)) {
2385 TileIndex end = GetOtherTunnelBridgeEnd(tile);
2386
2387 if (TunnelBridgeIsFree(tile, end, v).Succeeded()) {
2388 /* Free the reservation only if no other train is on the tiles. */
2389 SetTunnelBridgeReservation(tile, false);
2390 SetTunnelBridgeReservation(end, false);
2391
2392 if (_settings_client.gui.show_track_reservation) {
2393 if (IsBridge(tile)) {
2394 MarkBridgeDirty(tile);
2395 } else {
2396 MarkTileDirtyByTile(tile);
2397 MarkTileDirtyByTile(end);
2398 }
2399 }
2400 }
2401 }
2402 } else if (IsRailStationTile(tile)) {
2403 TileIndex new_tile = TileAddByDiagDir(tile, dir);
2404 /* If the new tile is not a further tile of the same station, we
2405 * clear the reservation for the whole platform. */
2406 if (!IsCompatibleTrainStationTile(new_tile, tile)) {
2407 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), false);
2408 }
2409 } else {
2410 /* Any other tile */
2411 UnreserveRailTrack(tile, TrackdirToTrack(track_dir));
2412 }
2413}
2414
2419 void FreeTrainTrackReservation(const Train *v)
2420{
2421 assert(v->IsFrontEngine());
2422
2423 TileIndex tile = v->tile;
2424 Trackdir td = v->GetVehicleTrackdir();
2425 bool free_tile = !(IsRailStationTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE));
2426 StationID station_id = IsRailStationTile(v->tile) ? GetStationIndex(v->tile) : StationID::Invalid();
2427
2428 /* Can't be holding a reservation if we enter a depot. */
2429 if (IsRailDepotTile(tile) && TrackdirToExitdir(td) != GetRailDepotDirection(tile)) return;
2430 if (v->track == TRACK_BIT_DEPOT) {
2431 /* Front engine is in a depot. We enter if some part is not in the depot. */
2432 for (const Train *u = v; u != nullptr; u = u->Next()) {
2433 if (u->track != TRACK_BIT_DEPOT || u->tile != v->tile) return;
2434 }
2435 }
2436 /* Don't free reservation if it's not ours. */
2437 if (TracksOverlap(GetReservedTrackbits(tile) | TrackToTrackBits(TrackdirToTrack(td)))) return;
2438
2439 CFollowTrackRail ft(v, GetAllCompatibleRailTypes(v->railtypes));
2440 while (ft.Follow(tile, td)) {
2441 tile = ft.new_tile;
2442 TrackdirBits bits = ft.new_td_bits & TrackBitsToTrackdirBits(GetReservedTrackbits(tile));
2443 td = RemoveFirstTrackdir(&bits);
2444 assert(bits == TRACKDIR_BIT_NONE);
2445
2446 if (!IsValidTrackdir(td)) break;
2447
2448 if (IsTileType(tile, MP_RAILWAY)) {
2449 if (HasSignalOnTrackdir(tile, td) && !IsPbsSignal(GetSignalType(tile, TrackdirToTrack(td)))) {
2450 /* Conventional signal along trackdir: remove reservation and stop. */
2451 UnreserveRailTrack(tile, TrackdirToTrack(td));
2452 break;
2453 }
2454 if (HasPbsSignalOnTrackdir(tile, td)) {
2455 if (GetSignalStateByTrackdir(tile, td) == SIGNAL_STATE_RED) {
2456 /* Red PBS signal? Can't be our reservation, would be green then. */
2457 break;
2458 } else {
2459 /* Turn the signal back to red. */
2460 SetSignalStateByTrackdir(tile, td, SIGNAL_STATE_RED);
2461 MarkTileDirtyByTile(tile);
2462 }
2463 } else if (HasPbsSignalOnTrackdir(tile, ReverseTrackdir(td))) {
2464 /* Reservation passes an opposing path signal. Mark signal for update to re-establish the proper default state. */
2465 AddSideToSignalBuffer(tile, TrackdirToExitdir(ReverseTrackdir(td)), v->owner);
2466 } else if (HasSignalOnTrackdir(tile, ReverseTrackdir(td)) && IsOnewaySignal(tile, TrackdirToTrack(td))) {
2467 break;
2468 }
2469 }
2470
2471 /* Don't free first station/bridge/tunnel if we are on it. */
2472 if (free_tile || (!(ft.is_station && GetStationIndex(ft.new_tile) == station_id) && !ft.is_tunnel && !ft.is_bridge)) ClearPathReservation(v, tile, td);
2473
2474 free_tile = true;
2475 }
2476
2477 UpdateSignalsInBuffer();
2478}
2479
2480static const uint8_t _initial_tile_subcoord[6][4][3] = {
2481{{ 15, 8, 1 }, { 0, 0, 0 }, { 0, 8, 5 }, { 0, 0, 0 }},
2482{{ 0, 0, 0 }, { 8, 0, 3 }, { 0, 0, 0 }, { 8, 15, 7 }},
2483{{ 0, 0, 0 }, { 7, 0, 2 }, { 0, 7, 6 }, { 0, 0, 0 }},
2484{{ 15, 8, 2 }, { 0, 0, 0 }, { 0, 0, 0 }, { 8, 15, 6 }},
2485{{ 15, 7, 0 }, { 8, 0, 4 }, { 0, 0, 0 }, { 0, 0, 0 }},
2486{{ 0, 0, 0 }, { 0, 0, 0 }, { 0, 8, 4 }, { 7, 15, 0 }},
2487};
2488
2502 static Track DoTrainPathfind(const Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found, bool do_track_reservation, PBSTileInfo *dest, TileIndex *final_dest)
2503{
2504 if (final_dest != nullptr) *final_dest = INVALID_TILE;
2505 return YapfTrainChooseTrack(v, tile, enterdir, tracks, path_found, do_track_reservation, dest, final_dest);
2506}
2507
2513 static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
2514{
2515 PBSTileInfo origin = FollowTrainReservation(v);
2516
2517 CFollowTrackRail ft(v);
2518
2519 std::vector<std::pair<TileIndex, Trackdir>> signals_set_to_red;
2520
2521 TileIndex tile = origin.tile;
2522 Trackdir cur_td = origin.trackdir;
2523 while (ft.Follow(tile, cur_td)) {
2524 if (KillFirstBit(ft.new_td_bits) == TRACKDIR_BIT_NONE) {
2525 /* Possible signal tile. */
2526 if (HasOnewaySignalBlockingTrackdir(ft.new_tile, FindFirstTrackdir(ft.new_td_bits))) break;
2527 }
2528
2529 if (Rail90DegTurnDisallowed(GetTileRailType(ft.old_tile), GetTileRailType(ft.new_tile))) {
2530 ft.new_td_bits &= ~TrackdirCrossesTrackdirs(ft.old_td);
2531 if (ft.new_td_bits == TRACKDIR_BIT_NONE) break;
2532 }
2533
2534 /* Station, depot or waypoint are a possible target. */
2535 bool target_seen = ft.is_station || (IsTileType(ft.new_tile, MP_RAILWAY) && !IsPlainRail(ft.new_tile));
2536 if (target_seen || KillFirstBit(ft.new_td_bits) != TRACKDIR_BIT_NONE) {
2537 /* Choice found or possible target encountered.
2538 * On finding a possible target, we need to stop and let the pathfinder handle the
2539 * remaining path. This is because we don't know if this target is in one of our
2540 * orders, so we might cause pathfinding to fail later on if we find a choice.
2541 * This failure would cause a bogous call to TryReserveSafePath which might reserve
2542 * a wrong path not leading to our next destination. */
2543 if (HasReservedTracks(ft.new_tile, TrackdirBitsToTrackBits(TrackdirReachesTrackdirs(ft.old_td)))) break;
2544
2545 /* If we did skip some tiles, backtrack to the first skipped tile so the pathfinder
2546 * actually starts its search at the first unreserved tile. */
2547 if (ft.tiles_skipped != 0) ft.new_tile -= TileOffsByDiagDir(ft.exitdir) * ft.tiles_skipped;
2548
2549 /* Choice found, path valid but not okay. Save info about the choice tile as well. */
2550 if (new_tracks != nullptr) *new_tracks = TrackdirBitsToTrackBits(ft.new_td_bits);
2551 if (enterdir != nullptr) *enterdir = ft.exitdir;
2552 return PBSTileInfo(ft.new_tile, ft.old_td, false);
2553 }
2554
2555 tile = ft.new_tile;
2556 cur_td = FindFirstTrackdir(ft.new_td_bits);
2557
2558 Trackdir rev_td = ReverseTrackdir(cur_td);
2559 if (IsSafeWaitingPosition(v, tile, cur_td, true, _settings_game.pf.forbid_90_deg)) {
2560 bool wp_free = IsWaitingPositionFree(v, tile, cur_td, _settings_game.pf.forbid_90_deg);
2561 if (!(wp_free && TryReserveRailTrack(tile, TrackdirToTrack(cur_td)))) break;
2562 /* Green path signal opposing the path? Turn to red. */
2563 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SIGNAL_STATE_GREEN) {
2564 signals_set_to_red.emplace_back(tile, rev_td);
2565 SetSignalStateByTrackdir(tile, rev_td, SIGNAL_STATE_RED);
2566 MarkTileDirtyByTile(tile);
2567 }
2568 /* Safe position is all good, path valid and okay. */
2569 return PBSTileInfo(tile, cur_td, true);
2570 }
2571
2572 if (!TryReserveRailTrack(tile, TrackdirToTrack(cur_td))) break;
2573
2574 /* Green path signal opposing the path? Turn to red. */
2575 if (HasPbsSignalOnTrackdir(tile, rev_td) && GetSignalStateByTrackdir(tile, rev_td) == SIGNAL_STATE_GREEN) {
2576 signals_set_to_red.emplace_back(tile, rev_td);
2577 SetSignalStateByTrackdir(tile, rev_td, SIGNAL_STATE_RED);
2578 MarkTileDirtyByTile(tile);
2579 }
2580 }
2581
2582 if (ft.err == CFollowTrackRail::EC_OWNER || ft.err == CFollowTrackRail::EC_NO_WAY) {
2583 /* End of line, path valid and okay. */
2584 return PBSTileInfo(ft.old_tile, ft.old_td, true);
2585 }
2586
2587 /* Sorry, can't reserve path, back out. */
2588 tile = origin.tile;
2589 cur_td = origin.trackdir;
2590 TileIndex stopped = ft.old_tile;
2591 Trackdir stopped_td = ft.old_td;
2592 while (tile != stopped || cur_td != stopped_td) {
2593 if (!ft.Follow(tile, cur_td)) break;
2594
2595 if (Rail90DegTurnDisallowed(GetTileRailType(ft.old_tile), GetTileRailType(ft.new_tile))) {
2596 ft.new_td_bits &= ~TrackdirCrossesTrackdirs(ft.old_td);
2597 assert(ft.new_td_bits != TRACKDIR_BIT_NONE);
2598 }
2599 assert(KillFirstBit(ft.new_td_bits) == TRACKDIR_BIT_NONE);
2600
2601 tile = ft.new_tile;
2602 cur_td = FindFirstTrackdir(ft.new_td_bits);
2603
2604 UnreserveRailTrack(tile, TrackdirToTrack(cur_td));
2605 }
2606
2607 /* Re-instate green signals we turned to red. */
2608 for (auto [sig_tile, td] : signals_set_to_red) {
2609 SetSignalStateByTrackdir(sig_tile, td, SIGNAL_STATE_GREEN);
2610 }
2611
2612 /* Path invalid. */
2613 return PBSTileInfo();
2614}
2615
2626 static bool TryReserveSafeTrack(const Train *v, TileIndex tile, Trackdir td, bool override_railtype)
2627{
2628 return YapfTrainFindNearestSafeTile(v, tile, td, override_railtype);
2629}
2630
2632 class VehicleOrderSaver {
2633private:
2634 Train *v;
2635 Order old_order;
2636 TileIndex old_dest_tile;
2637 StationID old_last_station_visited;
2638 VehicleOrderID index;
2639 bool suppress_implicit_orders;
2640 bool restored;
2641
2642public:
2643 VehicleOrderSaver(Train *_v) :
2644 v(_v),
2645 old_order(_v->current_order),
2646 old_dest_tile(_v->dest_tile),
2647 old_last_station_visited(_v->last_station_visited),
2648 index(_v->cur_real_order_index),
2649 suppress_implicit_orders(HasBit(_v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS)),
2650 restored(false)
2651 {
2652 }
2653
2657 void Restore()
2658 {
2659 this->v->current_order = this->old_order;
2660 this->v->dest_tile = this->old_dest_tile;
2661 this->v->last_station_visited = this->old_last_station_visited;
2662 AssignBit(this->v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS, suppress_implicit_orders);
2663 this->restored = true;
2664 }
2665
2669 ~VehicleOrderSaver()
2670 {
2671 if (!this->restored) this->Restore();
2672 }
2673
2679 bool SwitchToNextOrder(bool skip_first)
2680 {
2681 if (this->v->GetNumOrders() == 0) return false;
2682
2683 if (skip_first) ++this->index;
2684
2685 int depth = 0;
2686
2687 do {
2688 /* Wrap around. */
2689 if (this->index >= this->v->GetNumOrders()) this->index = 0;
2690
2691 Order *order = this->v->GetOrder(this->index);
2692 assert(order != nullptr);
2693
2694 switch (order->GetType()) {
2695 case OT_GOTO_DEPOT:
2696 /* Skip service in depot orders when the train doesn't need service. */
2697 if (order->GetDepotOrderType().Test(OrderDepotTypeFlag::Service) && !this->v->NeedsServicing()) break;
2698 [[fallthrough]];
2699 case OT_GOTO_STATION:
2700 case OT_GOTO_WAYPOINT:
2701 this->v->current_order = *order;
2702 return UpdateOrderDest(this->v, order, 0, true);
2703 case OT_CONDITIONAL: {
2704 VehicleOrderID next = ProcessConditionalOrder(order, this->v);
2705 if (next != INVALID_VEH_ORDER_ID) {
2706 depth++;
2707 this->index = next;
2708 /* Don't increment next, so no break here. */
2709 continue;
2710 }
2711 break;
2712 }
2713 default:
2714 break;
2715 }
2716 /* Don't increment inside the while because otherwise conditional
2717 * orders can lead to an infinite loop. */
2718 ++this->index;
2719 depth++;
2720 } while (this->index != this->v->cur_real_order_index && depth < this->v->GetNumOrders());
2721
2722 return false;
2723 }
2724};
2725
2726/* choose a track */
2727static Track ChooseTrainTrack(Train *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool force_res, bool *got_reservation, bool mark_stuck)
2728{
2729 Track best_track = INVALID_TRACK;
2730 bool do_track_reservation = _settings_game.pf.reserve_paths || force_res;
2731 bool changed_signal = false;
2732 TileIndex final_dest = INVALID_TILE;
2733
2734 assert((tracks & ~TRACK_BIT_MASK) == 0);
2735
2736 if (got_reservation != nullptr) *got_reservation = false;
2737
2738 /* Don't use tracks here as the setting to forbid 90 deg turns might have been switched between reservation and now. */
2739 TrackBits res_tracks = (TrackBits)(GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir));
2740 /* Do we have a suitable reserved track? */
2741 if (res_tracks != TRACK_BIT_NONE) return FindFirstTrack(res_tracks);
2742
2743 /* Quick return in case only one possible track is available */
2744 if (KillFirstBit(tracks) == TRACK_BIT_NONE) {
2745 Track track = FindFirstTrack(tracks);
2746 /* We need to check for signals only here, as a junction tile can't have signals. */
2747 if (track != INVALID_TRACK && HasPbsSignalOnTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir))) {
2748 do_track_reservation = true;
2749 changed_signal = true;
2750 SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(track, enterdir), SIGNAL_STATE_GREEN);
2751 } else if (!do_track_reservation) {
2752 return track;
2753 }
2754 best_track = track;
2755 }
2756
2757 PBSTileInfo res_dest(tile, INVALID_TRACKDIR, false);
2758 DiagDirection dest_enterdir = enterdir;
2759 if (do_track_reservation) {
2760 res_dest = ExtendTrainReservation(v, &tracks, &dest_enterdir);
2761 if (res_dest.tile == INVALID_TILE) {
2762 /* Reservation failed? */
2763 if (mark_stuck) MarkTrainAsStuck(v);
2764 if (changed_signal) SetSignalStateByTrackdir(tile, TrackEnterdirToTrackdir(best_track, enterdir), SIGNAL_STATE_RED);
2765 return FindFirstTrack(tracks);
2766 }
2767 if (res_dest.okay) {
2768 /* Got a valid reservation that ends at a safe target, quick exit. */
2769 if (got_reservation != nullptr) *got_reservation = true;
2770 if (changed_signal) MarkTileDirtyByTile(tile);
2771 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2772 return best_track;
2773 }
2774
2775 /* Check if the train needs service here, so it has a chance to always find a depot.
2776 * Also check if the current order is a service order so we don't reserve a path to
2777 * the destination but instead to the next one if service isn't needed. */
2778 CheckIfTrainNeedsService(v);
2779 if (v->current_order.IsType(OT_DUMMY) || v->current_order.IsType(OT_CONDITIONAL) || v->current_order.IsType(OT_GOTO_DEPOT)) ProcessOrders(v);
2780 }
2781
2782 /* Save the current train order. The destructor will restore the old order on function exit. */
2783 VehicleOrderSaver orders(v);
2784
2785 /* If the current tile is the destination of the current order and
2786 * a reservation was requested, advance to the next order.
2787 * Don't advance on a depot order as depots are always safe end points
2788 * for a path and no look-ahead is necessary. This also avoids a
2789 * problem with depot orders not part of the order list when the
2790 * order list itself is empty. */
2791 if (v->current_order.IsType(OT_LEAVESTATION)) {
2792 orders.SwitchToNextOrder(false);
2793 } else if (v->current_order.IsType(OT_LOADING) || (!v->current_order.IsType(OT_GOTO_DEPOT) && (
2794 v->current_order.IsType(OT_GOTO_STATION) ?
2795 IsRailStationTile(v->tile) && v->current_order.GetDestination() == GetStationIndex(v->tile) :
2796 v->tile == v->dest_tile))) {
2797 orders.SwitchToNextOrder(true);
2798 }
2799
2800 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2801 /* Pathfinders are able to tell that route was only 'guessed'. */
2802 bool path_found = true;
2803 TileIndex new_tile = res_dest.tile;
2804
2805 Track next_track = DoTrainPathfind(v, new_tile, dest_enterdir, tracks, path_found, do_track_reservation, &res_dest, &final_dest);
2806 if (new_tile == tile) best_track = next_track;
2807 v->HandlePathfindingResult(path_found);
2808 }
2809
2810 /* No track reservation requested -> finished. */
2811 if (!do_track_reservation) return best_track;
2812
2813 /* A path was found, but could not be reserved. */
2814 if (res_dest.tile != INVALID_TILE && !res_dest.okay) {
2815 if (mark_stuck) MarkTrainAsStuck(v);
2816 FreeTrainTrackReservation(v);
2817 return best_track;
2818 }
2819
2820 /* No possible reservation target found, we are probably lost. */
2821 if (res_dest.tile == INVALID_TILE) {
2822 /* Try to find any safe destination. */
2823 PBSTileInfo origin = FollowTrainReservation(v);
2824 if (TryReserveSafeTrack(v, origin.tile, origin.trackdir, false)) {
2825 TrackBits res = GetReservedTrackbits(tile) & DiagdirReachesTracks(enterdir);
2826 best_track = FindFirstTrack(res);
2827 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2828 if (got_reservation != nullptr) *got_reservation = true;
2829 if (changed_signal) MarkTileDirtyByTile(tile);
2830 } else {
2831 FreeTrainTrackReservation(v);
2832 if (mark_stuck) MarkTrainAsStuck(v);
2833 }
2834 return best_track;
2835 }
2836
2837 if (got_reservation != nullptr) *got_reservation = true;
2838
2839 /* Reservation target found and free, check if it is safe. */
2840 while (!IsSafeWaitingPosition(v, res_dest.tile, res_dest.trackdir, true, _settings_game.pf.forbid_90_deg)) {
2841 /* Extend reservation until we have found a safe position. */
2842 DiagDirection exitdir = TrackdirToExitdir(res_dest.trackdir);
2843 TileIndex next_tile = TileAddByDiagDir(res_dest.tile, exitdir);
2844 TrackBits reachable = TrackdirBitsToTrackBits((TrackdirBits)(GetTileTrackStatus(next_tile, TRANSPORT_RAIL, 0))) & DiagdirReachesTracks(exitdir);
2845 if (Rail90DegTurnDisallowed(GetTileRailType(res_dest.tile), GetTileRailType(next_tile))) {
2846 reachable &= ~TrackCrossesTracks(TrackdirToTrack(res_dest.trackdir));
2847 }
2848
2849 /* Get next order with destination. */
2850 if (orders.SwitchToNextOrder(true)) {
2851 PBSTileInfo cur_dest;
2852 bool path_found;
2853 DoTrainPathfind(v, next_tile, exitdir, reachable, path_found, true, &cur_dest, nullptr);
2854 if (cur_dest.tile != INVALID_TILE) {
2855 res_dest = cur_dest;
2856 if (res_dest.okay) continue;
2857 /* Path found, but could not be reserved. */
2858 FreeTrainTrackReservation(v);
2859 if (mark_stuck) MarkTrainAsStuck(v);
2860 if (got_reservation != nullptr) *got_reservation = false;
2861 changed_signal = false;
2862 break;
2863 }
2864 }
2865 /* No order or no safe position found, try any position. */
2866 if (!TryReserveSafeTrack(v, res_dest.tile, res_dest.trackdir, true)) {
2867 FreeTrainTrackReservation(v);
2868 if (mark_stuck) MarkTrainAsStuck(v);
2869 if (got_reservation != nullptr) *got_reservation = false;
2870 changed_signal = false;
2871 }
2872 break;
2873 }
2874
2875 TryReserveRailTrack(v->tile, TrackdirToTrack(v->GetVehicleTrackdir()));
2876
2877 if (changed_signal) MarkTileDirtyByTile(tile);
2878
2879 orders.Restore();
2880 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
2881 v->current_order.GetDepotActionType().Test(OrderDepotActionFlag::NearestDepot) &&
2882 final_dest != INVALID_TILE && IsRailDepotTile(final_dest)) {
2883 v->current_order.SetDestination(GetDepotIndex(final_dest));
2884 v->dest_tile = final_dest;
2885 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2886 }
2887
2888 return best_track;
2889}
2890
2899 bool TryPathReserve(Train *v, bool mark_as_stuck, bool first_tile_okay)
2900{
2901 assert(v->IsFrontEngine());
2902
2903 /* We have to handle depots specially as the track follower won't look
2904 * at the depot tile itself but starts from the next tile. If we are still
2905 * inside the depot, a depot reservation can never be ours. */
2906 if (v->track == TRACK_BIT_DEPOT) {
2907 if (HasDepotReservation(v->tile)) {
2908 if (mark_as_stuck) MarkTrainAsStuck(v);
2909 return false;
2910 } else {
2911 /* Depot not reserved, but the next tile might be. */
2912 TileIndex next_tile = TileAddByDiagDir(v->tile, GetRailDepotDirection(v->tile));
2913 if (HasReservedTracks(next_tile, DiagdirReachesTracks(GetRailDepotDirection(v->tile)))) return false;
2914 }
2915 }
2916
2917 Vehicle *other_train = nullptr;
2918 PBSTileInfo origin = FollowTrainReservation(v, &other_train);
2919 /* The path we are driving on is already blocked by some other train.
2920 * This can only happen in certain situations when mixing path and
2921 * block signals or when changing tracks and/or signals.
2922 * Exit here as doing any further reservations will probably just
2923 * make matters worse. */
2924 if (other_train != nullptr && other_train->index != v->index) {
2925 if (mark_as_stuck) MarkTrainAsStuck(v);
2926 return false;
2927 }
2928 /* If we have a reserved path and the path ends at a safe tile, we are finished already. */
2929 if (origin.okay && (v->tile != origin.tile || first_tile_okay)) {
2930 /* Can't be stuck then. */
2931 if (v->flags.Test(VehicleRailFlag::Stuck)) SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2932 v->flags.Reset(VehicleRailFlag::Stuck);
2933 return true;
2934 }
2935
2936 /* If we are in a depot, tentatively reserve the depot. */
2937 if (v->track == TRACK_BIT_DEPOT) {
2938 SetDepotReservation(v->tile, true);
2939 if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
2940 }
2941
2942 DiagDirection exitdir = TrackdirToExitdir(origin.trackdir);
2943 TileIndex new_tile = TileAddByDiagDir(origin.tile, exitdir);
2944 TrackBits reachable = TrackdirBitsToTrackBits(TrackStatusToTrackdirBits(GetTileTrackStatus(new_tile, TRANSPORT_RAIL, 0)) & DiagdirReachesTrackdirs(exitdir));
2945
2946 if (Rail90DegTurnDisallowed(GetTileRailType(origin.tile), GetTileRailType(new_tile))) reachable &= ~TrackCrossesTracks(TrackdirToTrack(origin.trackdir));
2947
2948 bool res_made = false;
2949 ChooseTrainTrack(v, new_tile, exitdir, reachable, true, &res_made, mark_as_stuck);
2950
2951 if (!res_made) {
2952 /* Free the depot reservation as well. */
2953 if (v->track == TRACK_BIT_DEPOT) SetDepotReservation(v->tile, false);
2954 return false;
2955 }
2956
2957 if (v->flags.Test(VehicleRailFlag::Stuck)) {
2958 v->wait_counter = 0;
2959 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
2960 }
2961 v->flags.Reset(VehicleRailFlag::Stuck);
2962 return true;
2963}
2964
2965
2966static bool CheckReverseTrain(const Train *v)
2967{
2968 if (_settings_game.difficulty.line_reverse_mode != 0 ||
2969 v->track == TRACK_BIT_DEPOT || v->track == TRACK_BIT_WORMHOLE ||
2970 !(v->direction & 1)) {
2971 return false;
2972 }
2973
2974 assert(v->track != TRACK_BIT_NONE);
2975
2976 return YapfTrainCheckReverse(v);
2977}
2978
2984 TileIndex Train::GetOrderStationLocation(StationID station)
2985{
2986 if (station == this->last_station_visited) this->last_station_visited = StationID::Invalid();
2987
2988 const Station *st = Station::Get(station);
2989 if (!st->facilities.Test(StationFacility::Train)) {
2990 /* The destination station has no trainstation tiles. */
2991 this->IncrementRealOrderIndex();
2992 return TileIndex{};
2993 }
2994
2995 return st->xy;
2996}
2997
2999 void Train::MarkDirty()
3000{
3001 Train *v = this;
3002 do {
3003 v->colourmap = PAL_NONE;
3004 v->UpdateViewport(true, false);
3005 } while ((v = v->Next()) != nullptr);
3006
3007 /* need to update acceleration and cached values since the goods on the train changed. */
3008 this->CargoChanged();
3009 this->UpdateAcceleration();
3010}
3011
3019 int Train::UpdateSpeed()
3020{
3021 switch (_settings_game.vehicle.train_acceleration_model) {
3022 default: NOT_REACHED();
3023 case AM_ORIGINAL:
3024 return this->DoUpdateSpeed(this->acceleration * (this->GetAccelerationStatus() == AS_BRAKE ? -4 : 2), 0, this->GetCurrentMaxSpeed());
3025
3026 case AM_REALISTIC:
3027 return this->DoUpdateSpeed(this->GetAcceleration(), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 2, this->GetCurrentMaxSpeed());
3028 }
3029}
3030
3036 static void TrainEnterStation(Train *v, StationID station)
3037{
3038 v->last_station_visited = station;
3039
3040 /* check if a train ever visited this station before */
3041 Station *st = Station::Get(station);
3042 if (!(st->had_vehicle_of_type & HVOT_TRAIN)) {
3043 st->had_vehicle_of_type |= HVOT_TRAIN;
3044 AddVehicleNewsItem(
3045 GetEncodedString(STR_NEWS_FIRST_TRAIN_ARRIVAL, st->index),
3046 v->owner == _local_company ? NewsType::ArrivalCompany : NewsType::ArrivalOther,
3047 v->index,
3048 st->index
3049 );
3050 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
3051 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
3052 }
3053
3054 v->force_proceed = TFP_NONE;
3055 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3056
3057 v->BeginLoading();
3058
3059 TriggerStationRandomisation(st, v->tile, StationRandomTrigger::VehicleArrives);
3060 TriggerStationAnimation(st, v->tile, StationAnimationTrigger::VehicleArrives);
3061}
3062
3063/* Check if the vehicle is compatible with the specified tile */
3064static inline bool CheckCompatibleRail(const Train *v, TileIndex tile)
3065{
3066 return IsTileOwner(tile, v->owner) &&
3067 (!v->IsFrontEngine() || v->compatible_railtypes.Test(GetRailType(tile)));
3068}
3069
3071 struct AccelerationSlowdownParams {
3072 uint8_t small_turn;
3073 uint8_t large_turn;
3074 uint8_t z_up;
3075 uint8_t z_down;
3076};
3077
3079 static const AccelerationSlowdownParams _accel_slowdown[] = {
3080 /* normal accel */
3081 {256 / 4, 256 / 2, 256 / 4, 2},
3082 {256 / 4, 256 / 2, 256 / 4, 2},
3083 {0, 256 / 2, 256 / 4, 2},
3084};
3085
3091 static inline void AffectSpeedByZChange(Train *v, int old_z)
3092{
3093 if (old_z == v->z_pos || _settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) return;
3094
3095 const AccelerationSlowdownParams *asp = &_accel_slowdown[static_cast<int>(v->GetAccelerationType())];
3096
3097 if (old_z < v->z_pos) {
3098 v->cur_speed -= (v->cur_speed * asp->z_up >> 8);
3099 } else {
3100 uint16_t spd = v->cur_speed + asp->z_down;
3101 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
3102 }
3103}
3104
3105static bool TrainMovedChangeSignals(TileIndex tile, DiagDirection dir)
3106{
3107 if (IsTileType(tile, MP_RAILWAY) &&
3108 GetRailTileType(tile) == RailTileType::Signals) {
3109 TrackdirBits tracks = TrackBitsToTrackdirBits(GetTrackBits(tile)) & DiagdirReachesTrackdirs(dir);
3110 Trackdir trackdir = FindFirstTrackdir(tracks);
3111 if (UpdateSignalsOnSegment(tile, TrackdirToExitdir(trackdir), GetTileOwner(tile)) == SIGSEG_PBS && HasSignalOnTrackdir(tile, trackdir)) {
3112 /* A PBS block with a non-PBS signal facing us? */
3113 if (!IsPbsSignal(GetSignalType(tile, TrackdirToTrack(trackdir)))) return true;
3114 }
3115 }
3116 return false;
3117}
3118
3120 void Train::ReserveTrackUnderConsist() const
3121{
3122 for (const Train *u = this; u != nullptr; u = u->Next()) {
3123 switch (u->track) {
3124 case TRACK_BIT_WORMHOLE:
3125 TryReserveRailTrack(u->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(u->tile)));
3126 break;
3127 case TRACK_BIT_DEPOT:
3128 break;
3129 default:
3130 TryReserveRailTrack(u->tile, TrackBitsToTrack(u->track));
3131 break;
3132 }
3133 }
3134}
3135
3142uint Train::Crash(bool flooded)
3143{
3144 uint victims = 0;
3145 if (this->IsFrontEngine()) {
3146 victims += 2; // driver
3147
3148 /* Remove the reserved path in front of the train if it is not stuck.
3149 * Also clear all reserved tracks the train is currently on. */
3150 if (!this->flags.Test(VehicleRailFlag::Stuck)) FreeTrainTrackReservation(this);
3151 for (const Train *v = this; v != nullptr; v = v->Next()) {
3152 ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3153 if (IsTileType(v->tile, MP_TUNNELBRIDGE)) {
3154 /* ClearPathReservation will not free the wormhole exit
3155 * if the train has just entered the wormhole. */
3156 SetTunnelBridgeReservation(GetOtherTunnelBridgeEnd(v->tile), false);
3157 }
3158 }
3159
3160 /* we may need to update crossing we were approaching,
3161 * but must be updated after the train has been marked crashed */
3162 TileIndex crossing = TrainApproachingCrossingTile(this);
3163 if (crossing != INVALID_TILE) UpdateLevelCrossing(crossing);
3164
3165 /* Remove the loading indicators (if any) */
3166 HideFillingPercent(&this->fill_percent_te_id);
3167 }
3168
3169 victims += this->GroundVehicleBase::Crash(flooded);
3170
3171 this->crash_anim_pos = flooded ? 4000 : 1; // max 4440, disappear pretty fast when flooded
3172 return victims;
3173}
3174
3181 static uint TrainCrashed(Train *v)
3182{
3183 uint victims = 0;
3184
3185 /* do not crash train twice */
3186 if (!v->vehstatus.Test(VehState::Crashed)) {
3187 victims = v->Crash();
3188 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3189 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_TRAIN, victims, v->owner));
3190 }
3191
3192 /* Try to re-reserve track under already crashed train too.
3193 * Crash() clears the reservation! */
3194 v->ReserveTrackUnderConsist();
3195
3196 return victims;
3197}
3198
3205 static uint CheckTrainCollision(Vehicle *v, Train *t)
3206{
3207 /* not a train or in depot */
3208 if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return 0;
3209
3210 /* do not crash into trains of another company. */
3211 if (v->owner != t->owner) return 0;
3212
3213 /* get first vehicle now to make most usual checks faster */
3214 Train *coll = Train::From(v)->First();
3215
3216 /* can't collide with own wagons */
3217 if (coll == t) return 0;
3218
3219 int x_diff = v->x_pos - t->x_pos;
3220 int y_diff = v->y_pos - t->y_pos;
3221
3222 /* Do fast calculation to check whether trains are not in close vicinity
3223 * and quickly reject trains distant enough for any collision.
3224 * Differences are shifted by 7, mapping range [-7 .. 8] into [0 .. 15]
3225 * Differences are then ORed and then we check for any higher bits */
3226 uint hash = (y_diff + 7) | (x_diff + 7);
3227 if (hash & ~15) return 0;
3228
3229 /* Slower check using multiplication */
3230 int min_diff = (Train::From(v)->gcache.cached_veh_length + 1) / 2 + (t->gcache.cached_veh_length + 1) / 2 - 1;
3231 if (x_diff * x_diff + y_diff * y_diff > min_diff * min_diff) return 0;
3232
3233 /* Happens when there is a train under bridge next to bridge head */
3234 if (abs(v->z_pos - t->z_pos) > 5) return 0;
3235
3236 /* Crash both trains. Two statements required to guarantee execution
3237 * order because RandomRange() is involved. */
3238 uint num_victims = TrainCrashed(t);
3239 return num_victims + TrainCrashed(coll);
3240}
3241
3249 static bool CheckTrainCollision(Train *v)
3250{
3251 /* can't collide in depot */
3252 if (v->track == TRACK_BIT_DEPOT) return false;
3253
3254 assert(v->track == TRACK_BIT_WORMHOLE || TileVirtXY(v->x_pos, v->y_pos) == v->tile);
3255
3256 uint num_victims = 0;
3257
3258 /* find colliding vehicles */
3259 if (v->track == TRACK_BIT_WORMHOLE) {
3260 for (Vehicle *u : VehiclesOnTile(v->tile)) {
3261 num_victims += CheckTrainCollision(u, v);
3262 }
3263 for (Vehicle *u : VehiclesOnTile(GetOtherTunnelBridgeEnd(v->tile))) {
3264 num_victims += CheckTrainCollision(u, v);
3265 }
3266 } else {
3267 for (Vehicle *u : VehiclesNearTileXY(v->x_pos, v->y_pos, 7)) {
3268 num_victims += CheckTrainCollision(u, v);
3269 }
3270 }
3271
3272 /* any dead -> no crash */
3273 if (num_victims == 0) return false;
3274
3275 AddTileNewsItem(GetEncodedString(STR_NEWS_TRAIN_CRASH, num_victims), NewsType::Accident, v->tile);
3276
3277 ModifyStationRatingAround(v->tile, v->owner, -160, 30);
3278 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_13_TRAIN_COLLISION, v);
3279 return true;
3280}
3281
3289 bool TrainController(Train *v, Vehicle *nomove, bool reverse)
3290{
3291 Train *first = v->First();
3292 Train *prev;
3293 bool direction_changed = false; // has direction of any part changed?
3294
3295 /* For every vehicle after and including the given vehicle */
3296 for (prev = v->Previous(); v != nomove; prev = v, v = v->Next()) {
3297 DiagDirection enterdir = DIAGDIR_BEGIN;
3298 bool update_signals_crossing = false; // will we update signals or crossing state?
3299
3300 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
3301 if (v->track != TRACK_BIT_WORMHOLE) {
3302 /* Not inside tunnel */
3303 if (gp.old_tile == gp.new_tile) {
3304 /* Staying in the old tile */
3305 if (v->track == TRACK_BIT_DEPOT) {
3306 /* Inside depot */
3307 gp.x = v->x_pos;
3308 gp.y = v->y_pos;
3309 } else {
3310 /* Not inside depot */
3311
3312 /* Reverse when we are at the end of the track already, do not move to the new position */
3313 if (v->IsFrontEngine() && !TrainCheckIfLineEnds(v, reverse)) return false;
3314
3315 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3316 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3317 goto invalid_rail;
3318 }
3319 if (vets.Test(VehicleEnterTileState::EnteredStation)) {
3320 /* The new position is the end of the platform */
3321 TrainEnterStation(v, GetStationIndex(gp.new_tile));
3322 }
3323 }
3324 } else {
3325 /* A new tile is about to be entered. */
3326
3327 /* Determine what direction we're entering the new tile from */
3328 enterdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
3329 assert(IsValidDiagDirection(enterdir));
3330
3331 /* Get the status of the tracks in the new tile and mask
3332 * away the bits that aren't reachable. */
3333 TrackStatus ts = GetTileTrackStatus(gp.new_tile, TRANSPORT_RAIL, 0, ReverseDiagDir(enterdir));
3334 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(enterdir);
3335
3336 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3337 TrackBits red_signals = TrackdirBitsToTrackBits(TrackStatusToRedSignals(ts) & reachable_trackdirs);
3338
3339 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3340 if (Rail90DegTurnDisallowed(GetTileRailType(gp.old_tile), GetTileRailType(gp.new_tile)) && prev == nullptr) {
3341 /* We allow wagons to make 90 deg turns, because forbid_90_deg
3342 * can be switched on halfway a turn */
3343 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3344 }
3345
3346 if (bits == TRACK_BIT_NONE) goto invalid_rail;
3347
3348 /* Check if the new tile constrains tracks that are compatible
3349 * with the current train, if not, bail out. */
3350 if (!CheckCompatibleRail(v, gp.new_tile)) goto invalid_rail;
3351
3352 TrackBits chosen_track;
3353 if (prev == nullptr) {
3354 /* Currently the locomotive is active. Determine which one of the
3355 * available tracks to choose */
3356 chosen_track = TrackToTrackBits(ChooseTrainTrack(v, gp.new_tile, enterdir, bits, false, nullptr, true));
3357 assert(chosen_track & (bits | GetReservedTrackbits(gp.new_tile)));
3358
3359 if (v->force_proceed != TFP_NONE && IsPlainRailTile(gp.new_tile) && HasSignals(gp.new_tile)) {
3360 /* For each signal we find decrease the counter by one.
3361 * We start at two, so the first signal we pass decreases
3362 * this to one, then if we reach the next signal it is
3363 * decreased to zero and we won't pass that new signal. */
3364 Trackdir dir = FindFirstTrackdir(trackdirbits);
3365 if (HasSignalOnTrackdir(gp.new_tile, dir) ||
3366 (HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(dir)) &&
3367 GetSignalType(gp.new_tile, TrackdirToTrack(dir)) != SIGTYPE_PBS)) {
3368 /* However, we do not want to be stopped by PBS signals
3369 * entered via the back. */
3370 v->force_proceed = (v->force_proceed == TFP_SIGNAL) ? TFP_STUCK : TFP_NONE;
3371 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
3372 }
3373 }
3374
3375 /* Check if it's a red signal and that force proceed is not clicked. */
3376 if ((red_signals & chosen_track) && v->force_proceed == TFP_NONE) {
3377 /* In front of a red signal */
3378 Trackdir i = FindFirstTrackdir(trackdirbits);
3379
3380 /* Don't handle stuck trains here. */
3381 if (v->flags.Test(VehicleRailFlag::Stuck)) return false;
3382
3383 if (!HasSignalOnTrackdir(gp.new_tile, ReverseTrackdir(i))) {
3384 v->cur_speed = 0;
3385 v->subspeed = 0;
3386 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3387 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_oneway_signal * Ticks::DAY_TICKS * 2) return false;
3388 } else if (HasSignalOnTrackdir(gp.new_tile, i)) {
3389 v->cur_speed = 0;
3390 v->subspeed = 0;
3391 v->progress = 255; // make sure that every bit of acceleration will hit the signal again, so speed stays 0.
3392 if (!_settings_game.pf.reverse_at_signals || ++v->wait_counter < _settings_game.pf.wait_twoway_signal * Ticks::DAY_TICKS * 2) {
3393 DiagDirection exitdir = TrackdirToExitdir(i);
3394 TileIndex o_tile = TileAddByDiagDir(gp.new_tile, exitdir);
3395
3396 exitdir = ReverseDiagDir(exitdir);
3397
3398 /* check if a train is waiting on the other side */
3399 if (!HasVehicleOnTile(o_tile, [&exitdir](const Vehicle *u) {
3400 if (u->type != VEH_TRAIN || u->vehstatus.Test(VehState::Crashed)) return false;
3401 const Train *t = Train::From(u);
3402
3403 /* not front engine of a train, inside wormhole or depot, crashed */
3404 if (!t->IsFrontEngine() || !(t->track & TRACK_BIT_MASK)) return false;
3405
3406 if (t->cur_speed > 5 || VehicleExitDir(t->direction, t->track) != exitdir) return false;
3407
3408 return true;
3409 })) return false;
3410 }
3411 }
3412
3413 /* If we would reverse but are currently in a PBS block and
3414 * reversing of stuck trains is disabled, don't reverse.
3415 * This does not apply if the reason for reversing is a one-way
3416 * signal blocking us, because a train would then be stuck forever. */
3417 if (!_settings_game.pf.reverse_at_signals && !HasOnewaySignalBlockingTrackdir(gp.new_tile, i) &&
3418 UpdateSignalsOnSegment(v->tile, enterdir, v->owner) == SIGSEG_PBS) {
3419 v->wait_counter = 0;
3420 return false;
3421 }
3422 goto reverse_train_direction;
3423 } else {
3424 TryReserveRailTrack(gp.new_tile, TrackBitsToTrack(chosen_track), false);
3425 }
3426 } else {
3427 /* The wagon is active, simply follow the prev vehicle. */
3428 if (prev->tile == gp.new_tile) {
3429 /* Choose the same track as prev */
3430 if (prev->track == TRACK_BIT_WORMHOLE) {
3431 /* Vehicles entering tunnels enter the wormhole earlier than for bridges.
3432 * However, just choose the track into the wormhole. */
3433 assert(IsTunnel(prev->tile));
3434 chosen_track = bits;
3435 } else {
3436 chosen_track = prev->track;
3437 }
3438 } else {
3439 /* Choose the track that leads to the tile where prev is.
3440 * This case is active if 'prev' is already on the second next tile, when 'v' just enters the next tile.
3441 * I.e. when the tile between them has only space for a single vehicle like
3442 * 1) horizontal/vertical track tiles and
3443 * 2) some orientations of tunnel entries, where the vehicle is already inside the wormhole at 8/16 from the tile edge.
3444 * Is also the train just reversing, the wagon inside the tunnel is 'on' the tile of the opposite tunnel entry.
3445 */
3446 static const TrackBits _connecting_track[DIAGDIR_END][DIAGDIR_END] = {
3447 {TRACK_BIT_X, TRACK_BIT_LOWER, TRACK_BIT_NONE, TRACK_BIT_LEFT },
3448 {TRACK_BIT_UPPER, TRACK_BIT_Y, TRACK_BIT_LEFT, TRACK_BIT_NONE },
3449 {TRACK_BIT_NONE, TRACK_BIT_RIGHT, TRACK_BIT_X, TRACK_BIT_UPPER},
3450 {TRACK_BIT_RIGHT, TRACK_BIT_NONE, TRACK_BIT_LOWER, TRACK_BIT_Y }
3451 };
3452 DiagDirection exitdir = DiagdirBetweenTiles(gp.new_tile, prev->tile);
3453 assert(IsValidDiagDirection(exitdir));
3454 chosen_track = _connecting_track[enterdir][exitdir];
3455 }
3456 chosen_track &= bits;
3457 }
3458
3459 /* Make sure chosen track is a valid track */
3460 assert(
3461 chosen_track == TRACK_BIT_X || chosen_track == TRACK_BIT_Y ||
3462 chosen_track == TRACK_BIT_UPPER || chosen_track == TRACK_BIT_LOWER ||
3463 chosen_track == TRACK_BIT_LEFT || chosen_track == TRACK_BIT_RIGHT);
3464
3465 /* Update XY to reflect the entrance to the new tile, and select the direction to use */
3466 const uint8_t *b = _initial_tile_subcoord[FindFirstBit(chosen_track)][enterdir];
3467 gp.x = (gp.x & ~0xF) | b[0];
3468 gp.y = (gp.y & ~0xF) | b[1];
3469 Direction chosen_dir = (Direction)b[2];
3470
3471 /* Call the landscape function and tell it that the vehicle entered the tile */
3472 auto vets = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
3473 if (vets.Test(VehicleEnterTileState::CannotEnter)) {
3474 goto invalid_rail;
3475 }
3476
3477 if (!vets.Test(VehicleEnterTileState::EnteredWormhole)) {
3478 Track track = FindFirstTrack(chosen_track);
3479 Trackdir tdir = TrackDirectionToTrackdir(track, chosen_dir);
3480 if (v->IsFrontEngine() && HasPbsSignalOnTrackdir(gp.new_tile, tdir)) {
3481 SetSignalStateByTrackdir(gp.new_tile, tdir, SIGNAL_STATE_RED);
3482 MarkTileDirtyByTile(gp.new_tile);
3483 }
3484
3485 /* Clear any track reservation when the last vehicle leaves the tile */
3486 if (v->Next() == nullptr) ClearPathReservation(v, v->tile, v->GetVehicleTrackdir());
3487
3488 v->tile = gp.new_tile;
3489
3490 if (GetTileRailType(gp.new_tile) != GetTileRailType(gp.old_tile)) {
3491 v->First()->ConsistChanged(CCF_TRACK);
3492 }
3493
3494 v->track = chosen_track;
3495 assert(v->track);
3496 }
3497
3498 /* We need to update signal status, but after the vehicle position hash
3499 * has been updated by UpdateInclination() */
3500 update_signals_crossing = true;
3501
3502 if (chosen_dir != v->direction) {
3503 if (prev == nullptr && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
3504 const AccelerationSlowdownParams *asp = &_accel_slowdown[static_cast<int>(v->GetAccelerationType())];
3505 DirDiff diff = DirDifference(v->direction, chosen_dir);
3506 v->cur_speed -= (diff == DIRDIFF_45RIGHT || diff == DIRDIFF_45LEFT ? asp->small_turn : asp->large_turn) * v->cur_speed >> 8;
3507 }
3508 direction_changed = true;
3509 v->direction = chosen_dir;
3510 }
3511
3512 if (v->IsFrontEngine()) {
3513 v->wait_counter = 0;
3514
3515 /* If we are approaching a crossing that is reserved, play the sound now. */
3516 TileIndex crossing = TrainApproachingCrossingTile(v);
3517 if (crossing != INVALID_TILE && HasCrossingReservation(crossing) && _settings_client.sound.ambient) SndPlayTileFx(SND_0E_LEVEL_CROSSING, crossing);
3518
3519 /* Always try to extend the reservation when entering a tile. */
3520 CheckNextTrainTile(v);
3521 }
3522
3523 if (vets.Test(VehicleEnterTileState::EnteredStation)) {
3524 /* The new position is the location where we want to stop */
3525 TrainEnterStation(v, GetStationIndex(gp.new_tile));
3526 }
3527 }
3528 } else {
3529 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && VehicleEnterTile(v, gp.new_tile, gp.x, gp.y).Test(VehicleEnterTileState::EnteredWormhole)) {
3530 /* Perform look-ahead on tunnel exit. */
3531 if (v->IsFrontEngine()) {
3532 TryReserveRailTrack(gp.new_tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(gp.new_tile)));
3533 CheckNextTrainTile(v);
3534 }
3535 /* Prevent v->UpdateInclination() being called with wrong parameters.
3536 * This could happen if the train was reversed inside the tunnel/bridge. */
3537 if (gp.old_tile == gp.new_tile) {
3538 gp.old_tile = GetOtherTunnelBridgeEnd(gp.old_tile);
3539 }
3540 } else {
3541 v->x_pos = gp.x;
3542 v->y_pos = gp.y;
3543 v->UpdatePosition();
3544 if (!v->vehstatus.Test(VehState::Hidden)) v->Vehicle::UpdateViewport(true);
3545 continue;
3546 }
3547 }
3548
3549 /* update image of train, as well as delta XY */
3550 v->UpdateDeltaXY();
3551
3552 v->x_pos = gp.x;
3553 v->y_pos = gp.y;
3554 v->UpdatePosition();
3555
3556 /* update the Z position of the vehicle */
3557 int old_z = v->UpdateInclination(gp.new_tile != gp.old_tile, false);
3558
3559 if (prev == nullptr) {
3560 /* This is the first vehicle in the train */
3561 AffectSpeedByZChange(v, old_z);
3562 }
3563
3564 if (update_signals_crossing) {
3565 if (v->IsFrontEngine()) {
3566 if (TrainMovedChangeSignals(gp.new_tile, enterdir)) {
3567 /* We are entering a block with PBS signals right now, but
3568 * not through a PBS signal. This means we don't have a
3569 * reservation right now. As a conventional signal will only
3570 * ever be green if no other train is in the block, getting
3571 * a path should always be possible. If the player built
3572 * such a strange network that it is not possible, the train
3573 * will be marked as stuck and the player has to deal with
3574 * the problem. */
3575 if ((!HasReservedTracks(gp.new_tile, v->track) &&
3576 !TryReserveRailTrack(gp.new_tile, FindFirstTrack(v->track))) ||
3577 !TryPathReserve(v)) {
3578 MarkTrainAsStuck(v);
3579 }
3580 }
3581 }
3582
3583 /* Signals can only change when the first
3584 * (above) or the last vehicle moves. */
3585 if (v->Next() == nullptr) {
3586 TrainMovedChangeSignals(gp.old_tile, ReverseDiagDir(enterdir));
3587 if (IsLevelCrossingTile(gp.old_tile)) UpdateLevelCrossing(gp.old_tile);
3588 }
3589 }
3590
3591 /* Do not check on every tick to save some computing time. */
3592 if (v->IsFrontEngine() && v->tick_counter % _settings_game.pf.path_backoff_interval == 0) CheckNextTrainTile(v);
3593 }
3594
3595 if (direction_changed) first->tcache.cached_max_curve_speed = first->GetCurveSpeedLimit();
3596
3597 return true;
3598
3599invalid_rail:
3600 /* We've reached end of line?? */
3601 if (prev != nullptr) FatalError("Disconnecting train");
3602
3603reverse_train_direction:
3604 if (reverse) {
3605 v->wait_counter = 0;
3606 v->cur_speed = 0;
3607 v->subspeed = 0;
3608 ReverseTrainDirection(v);
3609 }
3610
3611 return false;
3612}
3613
3614static bool IsRailStationPlatformOccupied(TileIndex tile)
3615{
3616 TileIndexDiff delta = TileOffsByAxis(GetRailStationAxis(tile));
3617
3618 for (TileIndex t = tile; IsCompatibleTrainStationTile(t, tile); t -= delta) {
3619 if (HasVehicleOnTile(t, IsTrain)) return true;
3620 }
3621 for (TileIndex t = tile + delta; IsCompatibleTrainStationTile(t, tile); t += delta) {
3622 if (HasVehicleOnTile(t, IsTrain)) return true;
3623 }
3624
3625 return false;
3626}
3627
3635 static void DeleteLastWagon(Train *v)
3636{
3637 Train *first = v->First();
3638
3639 /* Go to the last wagon and delete the link pointing there
3640 * new_last is then the one-before-last wagon, and v the last
3641 * one which will physically be removed */
3642 Train *new_last = v;
3643 for (; v->Next() != nullptr; v = v->Next()) new_last = v;
3644 new_last->SetNext(nullptr);
3645
3646 if (first != v) {
3647 /* Recalculate cached train properties */
3648 first->ConsistChanged(CCF_ARRANGE);
3649 /* Update the depot window if the first vehicle is in depot -
3650 * if v == first, then it is updated in PreDestructor() */
3651 if (first->track == TRACK_BIT_DEPOT) {
3652 SetWindowDirty(WC_VEHICLE_DEPOT, first->tile);
3653 }
3654 v->last_station_visited = first->last_station_visited; // for PreDestructor
3655 }
3656
3657 /* 'v' shouldn't be accessed after it has been deleted */
3658 TrackBits trackbits = v->track;
3659 TileIndex tile = v->tile;
3660 Owner owner = v->owner;
3661
3662 delete v;
3663 v = nullptr; // make sure nobody will try to read 'v' anymore
3664
3665 if (trackbits == TRACK_BIT_WORMHOLE) {
3666 /* Vehicle is inside a wormhole, v->track contains no useful value then. */
3667 trackbits = DiagDirToDiagTrackBits(GetTunnelBridgeDirection(tile));
3668 }
3669
3670 Track track = TrackBitsToTrack(trackbits);
3671 if (HasReservedTracks(tile, trackbits)) {
3672 UnreserveRailTrack(tile, track);
3673
3674 /* If there are still crashed vehicles on the tile, give the track reservation to them */
3675 TrackBits remaining_trackbits = TRACK_BIT_NONE;
3676 for (const Vehicle *u : VehiclesOnTile(tile)) {
3677 if (u->type != VEH_TRAIN || !u->vehstatus.Test(VehState::Crashed)) continue;
3678 TrackBits train_tbits = Train::From(u)->track;
3679 if (train_tbits == TRACK_BIT_WORMHOLE) {
3680 /* Vehicle is inside a wormhole, u->track contains no useful value then. */
3681 remaining_trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
3682 } else if (train_tbits != TRACK_BIT_DEPOT) {
3683 remaining_trackbits |= train_tbits;
3684 }
3685 }
3686
3687 /* It is important that these two are the first in the loop, as reservation cannot deal with every trackbit combination */
3688 assert(TRACK_BEGIN == TRACK_X && TRACK_Y == TRACK_BEGIN + 1);
3689 for (Track t : SetTrackBitIterator(remaining_trackbits)) TryReserveRailTrack(tile, t);
3690 }
3691
3692 /* check if the wagon was on a road/rail-crossing */
3693 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile);
3694
3695 if (IsRailStationTile(tile)) {
3696 bool occupied = IsRailStationPlatformOccupied(tile);
3697 DiagDirection dir = AxisToDiagDir(GetRailStationAxis(tile));
3698 SetRailStationPlatformReservation(tile, dir, occupied);
3699 SetRailStationPlatformReservation(tile, ReverseDiagDir(dir), occupied);
3700 }
3701
3702 /* Update signals */
3703 if (IsTileType(tile, MP_TUNNELBRIDGE) || IsRailDepotTile(tile)) {
3704 UpdateSignalsOnSegment(tile, INVALID_DIAGDIR, owner);
3705 } else {
3706 SetSignalsOnBothDir(tile, track, owner);
3707 }
3708}
3709
3714 static void ChangeTrainDirRandomly(Train *v)
3715{
3716 static const DirDiff delta[] = {
3717 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
3718 };
3719
3720 do {
3721 /* We don't need to twist around vehicles if they're not visible */
3722 if (!v->vehstatus.Test(VehState::Hidden)) {
3723 v->direction = ChangeDir(v->direction, delta[GB(Random(), 0, 2)]);
3724 /* Refrain from updating the z position of the vehicle when on
3725 * a bridge, because UpdateInclination() will put the vehicle under
3726 * the bridge in that case */
3727 if (v->track != TRACK_BIT_WORMHOLE) {
3728 v->UpdatePosition();
3729 v->UpdateInclination(false, true);
3730 } else {
3731 v->UpdateViewport(false, true);
3732 }
3733 }
3734 } while ((v = v->Next()) != nullptr);
3735}
3736
3742 static bool HandleCrashedTrain(Train *v)
3743{
3744 int state = ++v->crash_anim_pos;
3745
3746 if (state == 4 && !v->vehstatus.Test(VehState::Hidden)) {
3747 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
3748 }
3749
3750 uint32_t r;
3751 if (state <= 200 && Chance16R(1, 7, r)) {
3752 int index = (r * 10 >> 16);
3753
3754 Vehicle *u = v;
3755 do {
3756 if (--index < 0) {
3757 r = Random();
3758
3759 CreateEffectVehicleRel(u,
3760 GB(r, 8, 3) + 2,
3761 GB(r, 16, 3) + 2,
3762 GB(r, 0, 3) + 5,
3763 EV_EXPLOSION_SMALL);
3764 break;
3765 }
3766 } while ((u = u->Next()) != nullptr);
3767 }
3768
3769 if (state <= 240 && !(v->tick_counter & 3)) ChangeTrainDirRandomly(v);
3770
3771 if (state >= 4440 && !(v->tick_counter & 0x1F)) {
3772 bool ret = v->Next() != nullptr;
3773 DeleteLastWagon(v);
3774 return ret;
3775 }
3776
3777 return true;
3778}
3779
3781 static const uint16_t _breakdown_speeds[16] = {
3782 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 15
3783};
3784
3785
3794 static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
3795{
3796 /* Calc position within the current tile */
3797 uint x = v->x_pos & 0xF;
3798 uint y = v->y_pos & 0xF;
3799
3800 /* for diagonal directions, 'x' will be 0..15 -
3801 * for other directions, it will be 1, 3, 5, ..., 15 */
3802 switch (v->direction) {
3803 case DIR_N : x = ~x + ~y + 25; break;
3804 case DIR_NW: x = y; [[fallthrough]];
3805 case DIR_NE: x = ~x + 16; break;
3806 case DIR_E : x = ~x + y + 9; break;
3807 case DIR_SE: x = y; break;
3808 case DIR_S : x = x + y - 7; break;
3809 case DIR_W : x = ~y + x + 9; break;
3810 default: break;
3811 }
3812
3813 /* Do not reverse when approaching red signal. Make sure the vehicle's front
3814 * does not cross the tile boundary when we do reverse, but as the vehicle's
3815 * location is based on their center, use half a vehicle's length as offset.
3816 * Multiply the half-length by two for straight directions to compensate that
3817 * we only get odd x offsets there. */
3818 if (!signal && x + (v->gcache.cached_veh_length + 1) / 2 * (IsDiagonalDirection(v->direction) ? 1 : 2) >= TILE_SIZE) {
3819 /* we are too near the tile end, reverse now */
3820 v->cur_speed = 0;
3821 if (reverse) ReverseTrainDirection(v);
3822 return false;
3823 }
3824
3825 /* slow down */
3826 v->vehstatus.Set(VehState::TrainSlowing);
3827 uint16_t break_speed = _breakdown_speeds[x & 0xF];
3828 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3829
3830 return true;
3831}
3832
3833
3839 static bool TrainCanLeaveTile(const Train *v)
3840{
3841 /* Exit if inside a tunnel/bridge or a depot */
3842 if (v->track == TRACK_BIT_WORMHOLE || v->track == TRACK_BIT_DEPOT) return false;
3843
3844 TileIndex tile = v->tile;
3845
3846 /* entering a tunnel/bridge? */
3847 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
3848 DiagDirection dir = GetTunnelBridgeDirection(tile);
3849 if (DiagDirToDir(dir) == v->direction) return false;
3850 }
3851
3852 /* entering a depot? */
3853 if (IsRailDepotTile(tile)) {
3854 DiagDirection dir = ReverseDiagDir(GetRailDepotDirection(tile));
3855 if (DiagDirToDir(dir) == v->direction) return false;
3856 }
3857
3858 return true;
3859}
3860
3861
3869 static TileIndex TrainApproachingCrossingTile(const Train *v)
3870{
3871 assert(v->IsFrontEngine());
3872 assert(!v->vehstatus.Test(VehState::Crashed));
3873
3874 if (!TrainCanLeaveTile(v)) return INVALID_TILE;
3875
3876 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3877 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3878
3879 /* not a crossing || wrong axis || unusable rail (wrong type or owner) */
3880 if (!IsLevelCrossingTile(tile) || DiagDirToAxis(dir) == GetCrossingRoadAxis(tile) ||
3881 !CheckCompatibleRail(v, tile)) {
3882 return INVALID_TILE;
3883 }
3884
3885 return tile;
3886}
3887
3888
3896 static bool TrainCheckIfLineEnds(Train *v, bool reverse)
3897{
3898 /* First, handle broken down train */
3899
3900 int t = v->breakdown_ctr;
3901 if (t > 1) {
3902 v->vehstatus.Set(VehState::TrainSlowing);
3903
3904 uint16_t break_speed = _breakdown_speeds[GB(~t, 4, 4)];
3905 if (break_speed < v->cur_speed) v->cur_speed = break_speed;
3906 } else {
3907 v->vehstatus.Reset(VehState::TrainSlowing);
3908 }
3909
3910 if (!TrainCanLeaveTile(v)) return true;
3911
3912 /* Determine the non-diagonal direction in which we will exit this tile */
3913 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3914 /* Calculate next tile */
3915 TileIndex tile = v->tile + TileOffsByDiagDir(dir);
3916
3917 /* Determine the track status on the next tile */
3918 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_RAIL, 0, ReverseDiagDir(dir));
3919 TrackdirBits reachable_trackdirs = DiagdirReachesTrackdirs(dir);
3920
3921 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts) & reachable_trackdirs;
3922 TrackdirBits red_signals = TrackStatusToRedSignals(ts) & reachable_trackdirs;
3923
3924 /* We are sure the train is not entering a depot, it is detected above */
3925
3926 /* mask unreachable track bits if we are forbidden to do 90deg turns */
3927 TrackBits bits = TrackdirBitsToTrackBits(trackdirbits);
3928 if (Rail90DegTurnDisallowed(GetTileRailType(v->tile), GetTileRailType(tile))) {
3929 bits &= ~TrackCrossesTracks(FindFirstTrack(v->track));
3930 }
3931
3932 /* no suitable trackbits at all || unusable rail (wrong type or owner) */
3933 if (bits == TRACK_BIT_NONE || !CheckCompatibleRail(v, tile)) {
3934 return TrainApproachingLineEnd(v, false, reverse);
3935 }
3936
3937 /* approaching red signal */
3938 if ((trackdirbits & red_signals) != 0) return TrainApproachingLineEnd(v, true, reverse);
3939
3940 /* approaching a rail/road crossing? then make it red */
3941 if (IsLevelCrossingTile(tile)) MaybeBarCrossingWithSound(tile);
3942
3943 return true;
3944}
3945
3946
3947static bool TrainLocoHandler(Train *v, bool mode)
3948{
3949 /* train has crashed? */
3950 if (v->vehstatus.Test(VehState::Crashed)) {
3951 return mode ? true : HandleCrashedTrain(v); // 'this' can be deleted here
3952 }
3953
3954 if (v->force_proceed != TFP_NONE) {
3955 v->flags.Reset(VehicleRailFlag::Stuck);
3956 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
3957 }
3958
3959 /* train is broken down? */
3960 if (v->HandleBreakdown()) return true;
3961
3962 if (v->flags.Test(VehicleRailFlag::Reversing) && v->cur_speed == 0) {
3963 ReverseTrainDirection(v);
3964 }
3965
3966 /* exit if train is stopped */
3967 if (v->vehstatus.Test(VehState::Stopped) && v->cur_speed == 0) return true;
3968
3969 bool valid_order = !v->current_order.IsType(OT_NOTHING) && v->current_order.GetType() != OT_CONDITIONAL;
3970 if (ProcessOrders(v) && CheckReverseTrain(v)) {
3971 v->wait_counter = 0;
3972 v->cur_speed = 0;
3973 v->subspeed = 0;
3974 v->flags.Reset(VehicleRailFlag::LeavingStation);
3975 ReverseTrainDirection(v);
3976 return true;
3977 } else if (v->flags.Test(VehicleRailFlag::LeavingStation)) {
3978 /* Try to reserve a path when leaving the station as we
3979 * might not be marked as wanting a reservation, e.g.
3980 * when an overlength train gets turned around in a station. */
3981 DiagDirection dir = VehicleExitDir(v->direction, v->track);
3982 if (IsRailDepotTile(v->tile) || IsTileType(v->tile, MP_TUNNELBRIDGE)) dir = INVALID_DIAGDIR;
3983
3984 if (UpdateSignalsOnSegment(v->tile, dir, v->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
3985 TryPathReserve(v, true, true);
3986 }
3987 v->flags.Reset(VehicleRailFlag::LeavingStation);
3988 }
3989
3990 v->HandleLoading(mode);
3991
3992 if (v->current_order.IsType(OT_LOADING)) return true;
3993
3994 if (CheckTrainStayInDepot(v)) return true;
3995
3996 if (!mode) v->ShowVisualEffect();
3997
3998 /* We had no order but have an order now, do look ahead. */
3999 if (!valid_order && !v->current_order.IsType(OT_NOTHING)) {
4000 CheckNextTrainTile(v);
4001 }
4002
4003 /* Handle stuck trains. */
4004 if (!mode && v->flags.Test(VehicleRailFlag::Stuck)) {
4005 ++v->wait_counter;
4006
4007 /* Should we try reversing this tick if still stuck? */
4008 bool turn_around = v->wait_counter % (_settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) == 0 && _settings_game.pf.reverse_at_signals;
4009
4010 if (!turn_around && v->wait_counter % _settings_game.pf.path_backoff_interval != 0 && v->force_proceed == TFP_NONE) return true;
4011 if (!TryPathReserve(v)) {
4012 /* Still stuck. */
4013 if (turn_around) ReverseTrainDirection(v);
4014
4015 if (v->flags.Test(VehicleRailFlag::Stuck) && v->wait_counter > 2 * _settings_game.pf.wait_for_pbs_path * Ticks::DAY_TICKS) {
4016 /* Show message to player. */
4017 if (_settings_client.gui.lost_vehicle_warn && v->owner == _local_company) {
4018 AddVehicleAdviceNewsItem(AdviceType::TrainStuck, GetEncodedString(STR_NEWS_TRAIN_IS_STUCK, v->index), v->index);
4019 }
4020 v->wait_counter = 0;
4021 }
4022 /* Exit if force proceed not pressed, else reset stuck flag anyway. */
4023 if (v->force_proceed == TFP_NONE) return true;
4024 v->flags.Reset(VehicleRailFlag::Stuck);
4025 v->wait_counter = 0;
4026 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4027 }
4028 }
4029
4030 if (v->current_order.IsType(OT_LEAVESTATION)) {
4031 v->current_order.Free();
4032 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4033 return true;
4034 }
4035
4036 int j = v->UpdateSpeed();
4037
4038 /* we need to invalidate the widget if we are stopping from 'Stopping 0 km/h' to 'Stopped' */
4039 if (v->cur_speed == 0 && v->vehstatus.Test(VehState::Stopped)) {
4040 /* If we manually stopped, we're not force-proceeding anymore. */
4041 v->force_proceed = TFP_NONE;
4042 SetWindowDirty(WC_VEHICLE_VIEW, v->index);
4043 }
4044
4045 int adv_spd = v->GetAdvanceDistance();
4046 if (j < adv_spd) {
4047 /* if the vehicle has speed 0, update the last_speed field. */
4048 if (v->cur_speed == 0) v->SetLastSpeed();
4049 } else {
4050 TrainCheckIfLineEnds(v);
4051 /* Loop until the train has finished moving. */
4052 for (;;) {
4053 j -= adv_spd;
4054 TrainController(v, nullptr);
4055 /* Don't continue to move if the train crashed. */
4056 if (CheckTrainCollision(v)) break;
4057 /* Determine distance to next map position */
4058 adv_spd = v->GetAdvanceDistance();
4059
4060 /* No more moving this tick */
4061 if (j < adv_spd || v->cur_speed == 0) break;
4062
4063 OrderType order_type = v->current_order.GetType();
4064 /* Do not skip waypoints (incl. 'via' stations) when passing through at full speed. */
4065 if ((order_type == OT_GOTO_WAYPOINT || order_type == OT_GOTO_STATION) &&
4066 v->current_order.GetNonStopType().Test(OrderNonStopFlag::NoDestination) &&
4067 IsTileType(v->tile, MP_STATION) &&
4068 v->current_order.GetDestination() == GetStationIndex(v->tile)) {
4069 ProcessOrders(v);
4070 }
4071 }
4072 v->SetLastSpeed();
4073 }
4074
4075 for (Train *u = v; u != nullptr; u = u->Next()) {
4076 if (u->vehstatus.Test(VehState::Hidden)) continue;
4077
4078 u->UpdateViewport(false, false);
4079 }
4080
4081 if (v->progress == 0) v->progress = j; // Save unused spd for next time, if TrainController didn't set progress
4082
4083 return true;
4084}
4085
4090 Money Train::GetRunningCost() const
4091{
4092 Money cost = 0;
4093 const Train *v = this;
4094
4095 do {
4096 const Engine *e = v->GetEngine();
4097 if (e->VehInfo<RailVehicleInfo>().running_cost_class == INVALID_PRICE) continue;
4098
4099 uint cost_factor = GetVehicleProperty(v, PROP_TRAIN_RUNNING_COST_FACTOR, e->VehInfo<RailVehicleInfo>().running_cost);
4100 if (cost_factor == 0) continue;
4101
4102 /* Halve running cost for multiheaded parts */
4103 if (v->IsMultiheaded()) cost_factor /= 2;
4104
4105 cost += GetPrice(e->VehInfo<RailVehicleInfo>().running_cost_class, cost_factor, e->GetGRF());
4106 } while ((v = v->GetNextVehicle()) != nullptr);
4107
4108 return cost;
4109}
4110
4115 bool Train::Tick()
4116{
4117 this->tick_counter++;
4118
4119 if (this->IsFrontEngine()) {
4120 PerformanceAccumulator framerate(PFE_GL_TRAINS);
4121
4122 if (!this->vehstatus.Test(VehState::Stopped) || this->cur_speed > 0) this->running_ticks++;
4123
4124 this->current_order_time++;
4125
4126 if (!TrainLocoHandler(this, false)) return false;
4127
4128 return TrainLocoHandler(this, true);
4129 } else if (this->IsFreeWagon() && this->vehstatus.Test(VehState::Crashed)) {
4130 /* Delete flooded standalone wagon chain */
4131 if (++this->crash_anim_pos >= 4400) {
4132 delete this;
4133 return false;
4134 }
4135 }
4136
4137 return true;
4138}
4139
4144 static void CheckIfTrainNeedsService(Train *v)
4145{
4146 if (Company::Get(v->owner)->settings.vehicle.servint_trains == 0 || !v->NeedsAutomaticServicing()) return;
4147 if (v->IsChainInDepot()) {
4148 VehicleServiceInDepot(v);
4149 return;
4150 }
4151
4152 uint max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty;
4153
4154 FindDepotData tfdd = FindClosestTrainDepot(v, max_penalty);
4155 /* Only go to the depot if it is not too far out of our way. */
4156 if (tfdd.best_length == UINT_MAX || tfdd.best_length > max_penalty) {
4157 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
4158 /* If we were already heading for a depot but it has
4159 * suddenly moved farther away, we continue our normal
4160 * schedule? */
4161 v->current_order.MakeDummy();
4162 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4163 }
4164 return;
4165 }
4166
4167 DepotID depot = GetDepotIndex(tfdd.tile);
4168
4169 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
4170 v->current_order.GetDestination() != depot &&
4171 !Chance16(3, 16)) {
4172 return;
4173 }
4174
4175 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
4176 v->current_order.MakeGoToDepot(depot, OrderDepotTypeFlag::Service, OrderNonStopFlag::NoIntermediate, OrderDepotActionFlag::NearestDepot);
4177 v->dest_tile = tfdd.tile;
4178 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
4179}
4180
4182 void Train::OnNewCalendarDay()
4183{
4184 AgeVehicle(this);
4185}
4186
4188 void Train::OnNewEconomyDay()
4189{
4190 EconomyAgeVehicle(this);
4191
4192 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
4193
4194 if (this->IsFrontEngine()) {
4195 CheckVehicleBreakdown(this);
4196
4197 CheckIfTrainNeedsService(this);
4198
4199 CheckOrders(this);
4200
4201 /* update destination */
4202 if (this->current_order.IsType(OT_GOTO_STATION)) {
4203 TileIndex tile = Station::Get(this->current_order.GetDestination().ToStationID())->train_station.tile;
4204 if (tile != INVALID_TILE) this->dest_tile = tile;
4205 }
4206
4207 if (this->running_ticks != 0) {
4208 /* running costs */
4209 CommandCost cost(EXPENSES_TRAIN_RUN, this->GetRunningCost() * this->running_ticks / (CalendarTime::DAYS_IN_YEAR * Ticks::DAY_TICKS));
4210
4211 this->profit_this_year -= cost.GetCost();
4212 this->running_ticks = 0;
4213
4214 SubtractMoneyFromCompanyFract(this->owner, cost);
4215
4216 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
4217 SetWindowClassesDirty(WC_TRAINS_LIST);
4218 }
4219 }
4220}
4221
4226 Trackdir Train::GetVehicleTrackdir() const
4227{
4228 if (this->vehstatus.Test(VehState::Crashed)) return INVALID_TRACKDIR;
4229
4230 if (this->track == TRACK_BIT_DEPOT) {
4231 /* We'll assume the train is facing outwards */
4232 return DiagDirToDiagTrackdir(GetRailDepotDirection(this->tile)); // Train in depot
4233 }
4234
4235 if (this->track == TRACK_BIT_WORMHOLE) {
4236 /* train in tunnel or on bridge, so just use its direction and assume a diagonal track */
4237 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
4238 }
4239
4240 return TrackDirectionToTrackdir(FindFirstTrack(this->track), this->direction);
4241}
4242
4243uint16_t Train::GetMaxWeight() const
4244{
4245 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnitsInTrain(this->GetEngine()->DetermineCapacity(this));
4246
4247 /* Vehicle weight is not added for articulated parts. */
4248 if (!this->IsArticulatedPart()) {
4249 weight += GetVehicleProperty(this, PROP_TRAIN_WEIGHT, RailVehInfo(this->engine_type)->weight);
4250 }
4251
4252 /* Powered wagons have extra weight added. */
4253 if (this->flags.Test(VehicleRailFlag::PoweredWagon)) {
4254 weight += RailVehInfo(this->gcache.first_engine)->pow_wag_weight;
4255 }
4256
4257 return weight;
4258}
ai.hpp
Base functions for all AIs.
AddArticulatedParts
void AddArticulatedParts(Vehicle *first)
Add the remaining articulated parts to the given vehicle.
Definition articulated_vehicles.cpp:336
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:294
articulated_vehicles.h
Functions related to articulated vehicles.
CheckCargoCapacity
void CheckCargoCapacity(Vehicle *v)
Check the capacity of all vehicles in a chain and spread cargo if needed.
Definition autoreplace_cmd.cpp:107
VehicleFlag::BuiltAsPrototype
@ BuiltAsPrototype
Vehicle is a prototype (accepted as exclusive preview).
AssignBit
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
Definition bitmath_func.hpp:176
GB
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition bitmath_func.hpp:32
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition bitmath_func.hpp:121
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition bitmath_func.hpp:189
HasBit
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
KillFirstBit
constexpr T KillFirstBit(T value)
Clear the first bit in an integer.
Definition bitmath_func.hpp:226
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition bitmath_func.hpp:139
GetBridgeSpec
const BridgeSpec * GetBridgeSpec(BridgeType i)
Get the specification of a bridge type.
Definition bridge.h:60
IsBridgeTile
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
GetBridgeType
BridgeType GetBridgeType(Tile t)
Determines the type of bridge on a tile.
Definition bridge_map.h:56
IsBridge
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
Definition bridge_map.h:24
CargoType
uint8_t CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:21
IsValidCargoType
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:104
AI::NewEvent
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
Definition ai_core.cpp:235
BaseBitSet::Test
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Definition base_bitset_type.hpp:141
BaseBitSet::Reset
constexpr Timpl & Reset()
Reset all bits.
Definition base_bitset_type.hpp:83
BaseBitSet::Flip
constexpr Timpl & Flip(Tvalue_type value)
Flip the value-th bit.
Definition base_bitset_type.hpp:116
BaseBitSet::Set
constexpr Timpl & Set()
Set all bits.
Definition base_bitset_type.hpp:40
CommandCost
Common return value for all commands.
Definition command_type.h:24
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition command_type.h:98
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition command_type.h:118
CommandCost::Failed
bool Failed() const
Did this command fail?
Definition command_type.h:177
Engine
Definition engine_base.h:38
Engine::GetGRFID
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition engine.cpp:156
Engine::reliability_spd_dec
uint16_t reliability_spd_dec
Speed of reliability decay between services (per day).
Definition engine_base.h:50
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition engine_base.h:166
Engine::DetermineCapacity
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity=nullptr) const
Determines capacity of a given vehicle from scratch.
Definition engine.cpp:200
Engine::flags
EngineFlags flags
Flags of the engine.
Definition engine_base.h:57
Engine::original_image_index
uint8_t original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
Definition engine_base.h:61
Engine::GetLifeLengthInDays
TimerGameCalendar::Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
Definition engine.cpp:442
Engine::GetDefaultCargoType
CargoType GetDefaultCargoType() const
Determines the default cargo type of an engine.
Definition engine_base.h:95
Engine::reliability
uint16_t reliability
Current reliability of the engine.
Definition engine_base.h:49
EnumBitSet
Enum-as-bit-set wrapper.
Definition enum_type.hpp:177
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition game_core.cpp:136
OverflowSafeInt< int64_t >
PerformanceAccumulator
RAII class for measuring multi-step elements of performance.
Definition framerate_type.h:113
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:115
RailTypeInfo::curve_speed
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
Definition rail.h:195
Ticks::DAY_TICKS
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
Definition timer_game_tick.h:75
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition timer_game_calendar.h:33
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition timer_game_calendar.h:31
TimerGameConst< struct Calendar >::DAYS_IN_YEAR
static constexpr int DAYS_IN_YEAR
days per year
Definition timer_game_common.h:149
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition timer_game_economy.h:38
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition cargopacket.h:425
VehicleOrderSaver
This class will save the current order of a vehicle and restore it on destruction.
Definition train_cmd.cpp:2632
VehicleOrderSaver::Restore
void Restore()
Restore the saved order to the vehicle.
Definition train_cmd.cpp:2657
VehicleOrderSaver::~VehicleOrderSaver
~VehicleOrderSaver()
Restore the saved order to the vehicle, if Restore() has not already been called.
Definition train_cmd.cpp:2669
VehicleOrderSaver::SwitchToNextOrder
bool SwitchToNextOrder(bool skip_first)
Set the current vehicle order to the next order in the order list.
Definition train_cmd.cpp:2679
VehiclesNearTileXY
Iterate over all vehicles near a given world coordinate.
Definition vehicle_func.h:119
VehiclesOnTile
Iterate over all vehicles on a tile.
Definition vehicle_func.h:53
command_func.h
Functions related to commands.
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition command_func.h:28
DoCommandFlag::Execute
@ Execute
execute the given command
DoCommandFlag::NoCargoCapacityCheck
@ NoCargoCapacityCheck
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
DoCommandFlag::AutoReplace
@ AutoReplace
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
CheckOwnership
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
Definition company_cmd.cpp:381
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition company_cmd.cpp:55
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:56
SubtractMoneyFromCompanyFract
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
Subtract money from a company, including the money fraction.
Definition company_cmd.cpp:324
company_func.h
Functions related to companies.
GetDepotIndex
DepotID GetDepotIndex(Tile t)
Get the index of which depot is attached to the tile.
Definition depot_map.h:53
DirDifference
DirDiff DirDifference(Direction d0, Direction d1)
Calculate the difference between two directions.
Definition direction_func.h:68
DiagDirToDir
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
Definition direction_func.h:182
ReverseDiagDir
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Definition direction_func.h:118
ReverseDir
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Definition direction_func.h:54
IsValidDiagDirection
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Definition direction_func.h:21
ChangeDir
Direction ChangeDir(Direction d, DirDiff delta)
Change a direction by a given difference.
Definition direction_func.h:104
AxisToDiagDir
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Definition direction_func.h:232
IsDiagonalDirection
bool IsDiagonalDirection(Direction dir)
Checks if a given Direction is diagonal.
Definition direction_func.h:290
DiagDirToAxis
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
Definition direction_func.h:214
DirToDiagDir
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Definition direction_func.h:166
DirDiff
DirDiff
Enumeration for the difference between two directions.
Definition direction_type.h:63
DIRDIFF_90LEFT
@ DIRDIFF_90LEFT
Angle of 90 degrees left.
Definition direction_type.h:68
DIRDIFF_45LEFT
@ DIRDIFF_45LEFT
Angle of 45 degrees left.
Definition direction_type.h:69
DIRDIFF_45RIGHT
@ DIRDIFF_45RIGHT
Angle of 45 degrees right.
Definition direction_type.h:65
DIRDIFF_SAME
@ DIRDIFF_SAME
Both directions faces to the same direction.
Definition direction_type.h:64
DIRDIFF_90RIGHT
@ DIRDIFF_90RIGHT
Angle of 90 degrees right.
Definition direction_type.h:66
Direction
Direction
Defines the 8 directions on the map.
Definition direction_type.h:24
DIR_SW
@ DIR_SW
Southwest.
Definition direction_type.h:31
DIR_NW
@ DIR_NW
Northwest.
Definition direction_type.h:33
DIR_N
@ DIR_N
North.
Definition direction_type.h:26
DIR_SE
@ DIR_SE
Southeast.
Definition direction_type.h:29
DIR_S
@ DIR_S
South.
Definition direction_type.h:30
DIR_NE
@ DIR_NE
Northeast.
Definition direction_type.h:27
DIR_W
@ DIR_W
West.
Definition direction_type.h:32
DIR_E
@ DIR_E
East.
Definition direction_type.h:28
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition direction_type.h:123
DiagDirection
DiagDirection
Enumeration for diagonal directions.
Definition direction_type.h:78
DIAGDIR_END
@ DIAGDIR_END
Used for iterations.
Definition direction_type.h:84
DIAGDIR_BEGIN
@ DIAGDIR_BEGIN
Used for iterations.
Definition direction_type.h:79
INVALID_DIAGDIR
@ INVALID_DIAGDIR
Flag for an invalid DiagDirection.
Definition direction_type.h:85
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition economy.cpp:949
EXPENSES_TRAIN_RUN
@ EXPENSES_TRAIN_RUN
Running costs trains.
Definition economy_type.h:181
EXPENSES_NEW_VEHICLES
@ EXPENSES_NEW_VEHICLES
New vehicles.
Definition economy_type.h:180
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:610
effectvehicle_func.h
Functions related to effect vehicles.
EV_EXPLOSION_SMALL
@ EV_EXPLOSION_SMALL
Various explosions.
Definition effectvehicle_func.h:24
EV_EXPLOSION_LARGE
@ EV_EXPLOSION_LARGE
Various explosions.
Definition effectvehicle_func.h:22
EngineMiscFlag::RailFlips
@ RailFlips
Rail vehicle has old depot-flip handling.
EngineMiscFlag::RailTilts
@ RailTilts
Rail vehicle tilts in curves.
VE_DISABLE_WAGON_POWER
@ VE_DISABLE_WAGON_POWER
Flag to disable wagon power.
Definition engine_type.h:68
EngineFlag::ExclusivePreview
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition engine_type.h:34
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition engine_type.h:33
error.h
Functions related to errors.
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
ShowErrorMessage
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Definition error_gui.cpp:296
error_func.h
Error reporting related functions.
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition fluidsynth.cpp:25
framerate_type.h
Types for recording game performance data.
PFE_GL_TRAINS
@ PFE_GL_TRAINS
Time spent processing trains.
Definition framerate_type.h:50
game.hpp
Base functions for all Games.
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
PaletteID
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
AS_BRAKE
@ AS_BRAKE
We want to stop.
Definition ground_vehicle.hpp:23
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:57
GVF_GOINGDOWN_BIT
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
Definition ground_vehicle.hpp:56
GVF_GOINGUP_BIT
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
Definition ground_vehicle.hpp:55
UpdateTrainGroupID
void UpdateTrainGroupID(Train *v)
Recalculates the groupID of a train.
Definition group_cmd.cpp:793
SetTrainGroupID
void SetTrainGroupID(Train *v, GroupID grp)
Affect the groupID of a train to new_g.
Definition group_cmd.cpp:765
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:2128
DEFAULT_GROUP
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
GetTileTrackStatus
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
Definition landscape.cpp:560
GetSlopePixelZ
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Definition landscape.cpp:307
BorderFlag::Random
@ Random
Randomise borders.
DiagdirBetweenTiles
DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
Definition map_func.h:636
TileVirtXY
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:416
TileAddByDiagDir
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:624
TileOffsByAxis
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:568
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:438
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:428
TileOffsByDiagDir
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:583
TileIndexDiff
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
abs
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
CeilDiv
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition math_func.hpp:310
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
misc_cmd.h
Miscellaneous command definitions.
HideFillingPercent
void HideFillingPercent(TextEffectID *te_id)
Hide vehicle loading indicators.
Definition misc_gui.cpp:586
_networking
bool _networking
are we in networking mode?
Definition network.cpp:67
network.h
Basic functions/variables used all over the place.
ClientID
ClientID
'Unique' identifier to be given to clients
Definition network_type.h:43
newgrf.h
Base for the NewGRF implementation.
VehicleCallbackMask::ArticEngine
@ ArticEngine
Add articulated engines (trains and road vehicles)
VehicleCallbackMask::Length
@ Length
Vehicle length (trains and road vehicles)
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:35
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:74
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition newgrf_callbacks.h:439
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition newgrf_commons.cpp:517
GRFBug::VehCapacity
@ VehCapacity
Capacity of vehicle changes when not refitting or arranging.
newgrf_debug.h
Functions/types related to NewGRF debugging.
InvalidateNewGRFInspectWindow
void InvalidateNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Invalidate the inspect window for a given feature and index.
Definition newgrf_debug_gui.cpp:710
DeleteNewGRFInspectWindow
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
Definition newgrf_debug_gui.cpp:726
GetVehicleCallbackParent
uint16_t GetVehicleCallbackParent(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, const Vehicle *parent, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles with a different vehicle for parent scope.
Definition newgrf_engine.cpp:1215
TestVehicleBuildProbability
std::optional< bool > TestVehicleBuildProbability(Vehicle *v, EngineID engine, BuildProbabilityType type)
Test for vehicle build probability type.
Definition newgrf_engine.cpp:1251
UsesWagonOverride
bool UsesWagonOverride(const Vehicle *v)
Check if a wagon is currently using a wagon override.
Definition newgrf_engine.cpp:1182
GetVehicleCallback
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
Definition newgrf_engine.cpp:1198
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition newgrf_properties.h:28
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition newgrf_properties.h:29
PROP_TRAIN_WEIGHT
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
Definition newgrf_properties.h:25
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition newgrf_properties.h:30
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition newgrf_properties.h:23
PROP_TRAIN_SPEED
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
Definition newgrf_properties.h:21
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:143
newgrf_sound.h
Functions related to NewGRF provided sounds.
VSE_START
@ VSE_START
Vehicle starting, i.e. leaving, the station.
Definition newgrf_sound.h:19
TriggerStationRandomisation
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
Definition newgrf_station.cpp:949
newgrf_station.h
Header file for NewGRF stations.
GetGRFStringID
StringID GetGRFStringID(uint32_t grfid, GRFStringID stringid)
Returns the index for this stringid associated with its grfID.
Definition newgrf_text.cpp:580
newgrf_text.h
Header of Action 04 "universal holder" structure and functions.
GRFSTR_MISC_GRF_TEXT
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
Definition newgrf_text_type.h:18
news_func.h
Functions related to news.
AddVehicleNewsItem
void AddVehicleNewsItem(EncodedString &&headline, NewsType type, VehicleID vehicle, StationID station=StationID::Invalid())
Adds a newsitem referencing a vehicle.
Definition news_func.h:30
AddVehicleAdviceNewsItem
void AddVehicleAdviceNewsItem(AdviceType advice_type, EncodedString &&headline, VehicleID vehicle)
Adds a vehicle-advice news item.
Definition news_func.h:40
NewsType::ArrivalCompany
@ ArrivalCompany
First vehicle arrived for company.
NewsType::ArrivalOther
@ ArrivalOther
First vehicle arrived for competitor.
NewsType::Accident
@ Accident
An accident or disaster has occurred.
AdviceType::TrainStuck
@ TrainStuck
The train got stuck and needs to be unstuck manually.
PauseMode::Error
@ Error
A game paused because a (critical) error.
order_backup.h
Functions related to order backups.
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:2078
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:1949
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:1681
DeleteVehicleOrders
void DeleteVehicleOrders(Vehicle *v, bool keep_orderlist, bool reset_order_indices)
Delete all orders from a vehicle.
Definition order_cmd.cpp:1833
ProcessConditionalOrder
VehicleOrderID ProcessConditionalOrder(const Order *order, const Vehicle *v)
Process a conditional order and determine the next order.
Definition order_cmd.cpp:1919
OrderStopLocation
OrderStopLocation
Where to stop the trains.
Definition order_type.h:97
OrderStopLocation::NearEnd
@ NearEnd
Stop at the near end of the platform.
OrderStopLocation::FarEnd
@ FarEnd
Stop at the far end of the platform.
OrderStopLocation::Middle
@ Middle
Stop at the middle of the platform.
OrderNonStopFlag::NoDestination
@ NoDestination
The vehicle will stop at any station it passes except the destination, aka via.
OrderNonStopFlag::NoIntermediate
@ NoIntermediate
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
VehicleOrderID
uint8_t VehicleOrderID
The index of an order within its current vehicle (not pool related)
Definition order_type.h:18
OrderDepotActionFlag::NearestDepot
@ NearestDepot
Send the vehicle to the nearest depot.
OrderDepotTypeFlag::Service
@ Service
This depot order is because of the servicing limit.
INVALID_VEH_ORDER_ID
static const VehicleOrderID INVALID_VEH_ORDER_ID
Invalid vehicle order index (sentinel)
Definition order_type.h:39
OrderType
OrderType
Order types.
Definition order_type.h:50
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
FollowTrainReservation
PBSTileInfo FollowTrainReservation(const Train *v, Vehicle **train_on_res)
Follow a train reservation to the last tile.
Definition pbs.cpp:289
TryReserveRailTrack
bool TryReserveRailTrack(TileIndex tile, Track t, bool trigger_stations)
Try to reserve a specific track on a tile.
Definition pbs.cpp:80
IsWaitingPositionFree
bool IsWaitingPositionFree(const Train *v, TileIndex tile, Trackdir trackdir, bool forbid_90deg)
Check if a safe position is free.
Definition pbs.cpp:427
UnreserveRailTrack
void UnreserveRailTrack(TileIndex tile, Track t)
Lift the reservation of a specific track on a tile.
Definition pbs.cpp:144
IsSafeWaitingPosition
bool IsSafeWaitingPosition(const Train *v, TileIndex tile, Trackdir trackdir, bool include_line_end, bool forbid_90deg)
Determine whether a certain track on a tile is a safe position to end a path.
Definition pbs.cpp:381
HasReservedTracks
bool HasReservedTracks(TileIndex tile, TrackBits tracks)
Check whether some of tracks is reserved on a tile.
Definition pbs.h:58
GetTileRailType
RailType GetTileRailType(Tile tile)
Return the rail type of tile, or INVALID_RAILTYPE if this is no rail tile.
Definition rail.cpp:37
TicksToLeaveDepot
int TicksToLeaveDepot(const Train *v)
Compute number of ticks when next wagon will leave a depot.
Definition rail_cmd.cpp:2926
GetAllPoweredRailTypes
RailTypes GetAllPoweredRailTypes(RailTypes railtypes)
Returns all powered railtypes for a set of railtypes.
Definition rail.h:324
IsCompatibleRail
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:351
HasPowerOnRail
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:376
Rail90DegTurnDisallowed
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:410
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:300
GetAllCompatibleRailTypes
RailTypes GetAllCompatibleRailTypes(RailTypes railtypes)
Returns all compatible railtypes for a set of railtypes.
Definition rail.h:312
TrainList
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition rail_cmd.cpp:44
HasOnewaySignalBlockingTrackdir
bool HasOnewaySignalBlockingTrackdir(Tile 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:474
GetRailTileType
static RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition rail_map.h:36
IsPlainRail
static bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition rail_map.h:49
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
HasSignalOnTrackdir
bool HasSignalOnTrackdir(Tile tile, Trackdir trackdir)
Checks for the presence of signals along the given trackdir on the given rail tile.
Definition rail_map.h:425
GetTrackBits
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
IsPlainRailTile
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
RailTileType::Signals
@ Signals
Normal rail tile with signals.
GetRailDepotTrack
Track GetRailDepotTrack(Tile t)
Returns the track of a depot, ignoring direction.
Definition rail_map.h:182
GetRailDepotDirection
DiagDirection GetRailDepotDirection(Tile t)
Returns the direction the depot is facing to.
Definition rail_map.h:171
SetSignalStateByTrackdir
void SetSignalStateByTrackdir(Tile tile, Trackdir trackdir, SignalState state)
Sets the state of the signal along the given trackdir.
Definition rail_map.h:448
HasSignalOnTrack
bool HasSignalOnTrack(Tile tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile.
Definition rail_map.h:412
HasPbsSignalOnTrackdir
bool HasPbsSignalOnTrackdir(Tile tile, Trackdir td)
Is a pbs signal present along the trackdir?
Definition rail_map.h:462
IsOnewaySignal
bool IsOnewaySignal(Tile t, Track track)
One-way signals can't be passed the 'wrong' way.
Definition rail_map.h:318
SetDepotReservation
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:269
HasDepotReservation
bool HasDepotReservation(Tile t)
Get the reservation state of the depot.
Definition rail_map.h:257
HasSignals
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
GetSignalStateByTrackdir
SignalState GetSignalStateByTrackdir(Tile tile, Trackdir trackdir)
Gets the state of the signal along the given trackdir.
Definition rail_map.h:437
IsRailDepotTile
static bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition rail_map.h:105
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition rail_type.h:27
random_func.hpp
Pseudo random number generator.
Chance16
bool Chance16(const uint32_t a, const uint32_t b, const std::source_location location=std::source_location::current())
Flips a coin with given probability.
Definition random_func.hpp:134
Chance16R
bool Chance16R(const uint32_t a, const uint32_t b, uint32_t &r, const std::source_location location=std::source_location::current())
Flips a coin with a given probability and saves the randomize-number in a variable.
Definition random_func.hpp:154
UpdateLevelCrossing
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
Definition train_cmd.cpp:1791
HasCrossingReservation
bool HasCrossingReservation(Tile t)
Get the reservation state of the rail crossing.
Definition road_map.h:364
IsLevelCrossingTile
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:79
GetCrossingRoadAxis
Axis GetCrossingRoadAxis(Tile t)
Get the road axis of a level crossing.
Definition road_map.h:309
SetCrossingBarred
void SetCrossingBarred(Tile t, bool barred)
Set the bar state of a level crossing.
Definition road_map.h:412
GetCrossingRailAxis
Axis GetCrossingRailAxis(Tile t)
Get the rail axis of a level crossing.
Definition road_map.h:321
IsCrossingBarred
bool IsCrossingBarred(Tile t)
Check if the level crossing is barred.
Definition road_map.h:400
SetCrossingReservation
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition road_map.h:377
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
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:647
UpdateSignalsInBuffer
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
Definition signal.cpp:573
AddSideToSignalBuffer
void AddSideToSignalBuffer(TileIndex tile, DiagDirection side, Owner owner)
Add side of tile to signal update buffer.
Definition signal.cpp:621
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:665
SigSegState
SigSegState
State of the signal segment.
Definition signal_func.h:49
SIGSEG_PBS
@ SIGSEG_PBS
Segment is a PBS segment.
Definition signal_func.h:52
SIGSEG_FULL
@ SIGSEG_FULL
Occupied by a train.
Definition signal_func.h:51
SIGTYPE_PBS
@ SIGTYPE_PBS
normal pbs signal
Definition signal_type.h:28
SIGNAL_STATE_RED
@ SIGNAL_STATE_RED
The signal is red.
Definition signal_type.h:43
SIGNAL_STATE_GREEN
@ SIGNAL_STATE_GREEN
The signal is green.
Definition signal_type.h:44
sound_func.h
Functions related to sound.
SoundFx
SoundFx
Sound effects from baseset.
Definition sound_type.h:45
SND_04_DEPARTURE_STEAM
@ SND_04_DEPARTURE_STEAM
2 == 0x02 Station departure: steam engine
Definition sound_type.h:49
SND_41_DEPARTURE_MAGLEV
@ SND_41_DEPARTURE_MAGLEV
65 == 0x41 Station departure: maglev engine
Definition sound_type.h:112
SND_13_TRAIN_COLLISION
@ SND_13_TRAIN_COLLISION
15 == 0x11 Train+train crash
Definition sound_type.h:64
SND_0E_LEVEL_CROSSING
@ SND_0E_LEVEL_CROSSING
12 == 0x0C Train passes through level crossing
Definition sound_type.h:59
SND_0A_DEPARTURE_TRAIN
@ SND_0A_DEPARTURE_TRAIN
8 == 0x08 Station departure: diesel and electric engine
Definition sound_type.h:55
SND_47_DEPARTURE_MONORAIL
@ SND_47_DEPARTURE_MONORAIL
71 == 0x47 Station departure: monorail engine
Definition sound_type.h:118
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1619
ModifyStationRatingAround
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
Definition station_cmd.cpp:4388
IsRailWaypointTile
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
Definition station_map.h:123
IsCompatibleTrainStationTile
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
Definition station_map.h:544
IsRailStationTile
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Definition station_map.h:102
GetStationIndex
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:28
GetRailStationAxis
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
Definition station_map.h:503
HVOT_TRAIN
@ HVOT_TRAIN
Station has seen a train.
Definition station_type.h:66
StationFacility::Train
@ Train
Station with train station.
StationRandomTrigger::VehicleArrives
@ VehicleArrives
Trigger platform when train arrives.
StationAnimationTrigger::VehicleArrives
@ VehicleArrives
Trigger platform when train arrives.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
GetEncodedString
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
strings_func.h
Functions related to OTTD's strings.
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition strings_type.h:19
AccelerationSlowdownParams
Data structure for storing engine speed changes of an acceleration type.
Definition train_cmd.cpp:3071
AccelerationSlowdownParams::large_turn
uint8_t large_turn
Speed change due to a large turn.
Definition train_cmd.cpp:3073
AccelerationSlowdownParams::z_up
uint8_t z_up
Fraction to remove when moving up.
Definition train_cmd.cpp:3074
AccelerationSlowdownParams::small_turn
uint8_t small_turn
Speed change due to a small turn.
Definition train_cmd.cpp:3072
AccelerationSlowdownParams::z_down
uint8_t z_down
Fraction to add when moving down.
Definition train_cmd.cpp:3075
BaseConsist::name
std::string name
Name of vehicle.
Definition base_consist.h:34
BaseConsist::current_order_time
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
Definition base_consist.h:37
BaseConsist::cur_real_order_index
VehicleOrderID cur_real_order_index
The index to the current real (non-implicit) order.
Definition base_consist.h:47
BaseConsist::vehicle_flags
VehicleFlags vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition base_consist.h:50
BaseConsist::ResetDepotUnbunching
void ResetDepotUnbunching()
Resets all the data used for depot unbunching.
Definition base_consist.cpp:49
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition base_station_base.h:59
BaseStation::facilities
StationFacilities facilities
The facilities that this station has.
Definition base_station_base.h:69
BaseStation::train_station
TileArea train_station
Tile area the train 'station' part covers.
Definition base_station_base.h:83
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition vehicle_type.h:51
BridgeSpec::speed
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition bridge.h:39
CFollowTrackT
Track follower helper template class (can serve pathfinders and vehicle controllers).
Definition follow_track.hpp:28
CFollowTrackT::Follow
bool Follow(TileIndex old_tile, Trackdir old_td)
main follower routine.
Definition follow_track.hpp:120
CFollowTrackT::is_tunnel
bool is_tunnel
last turn passed tunnel
Definition follow_track.hpp:45
CFollowTrackT::is_bridge
bool is_bridge
last turn passed bridge ramp
Definition follow_track.hpp:46
CFollowTrackT::tiles_skipped
int tiles_skipped
number of skipped tunnel or station tiles
Definition follow_track.hpp:48
CFollowTrackT::exitdir
DiagDirection exitdir
exit direction (leaving the old tile)
Definition follow_track.hpp:44
CFollowTrackT::new_td_bits
TrackdirBits new_td_bits
the new set of available trackdirs
Definition follow_track.hpp:43
CFollowTrackT::new_tile
TileIndex new_tile
the new tile (the vehicle has entered)
Definition follow_track.hpp:42
CFollowTrackT::old_td
Trackdir old_td
the trackdir (the vehicle was on) before move
Definition follow_track.hpp:41
CFollowTrackT::is_station
bool is_station
last turn passed station
Definition follow_track.hpp:47
CFollowTrackT::old_tile
TileIndex old_tile
the origin (vehicle moved from) before move
Definition follow_track.hpp:40
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:137
ClientSettings::sound
SoundSettings sound
sound effect settings
Definition settings_type.h:653
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition settings_type.h:650
ClosestDepot
Structure to return information about the closest depot location, and whether it could be found.
Definition vehicle_base.h:192
CommandHelper
Definition command_func.h:84
Coord2D< int >
Coord2D::y
T y
Y coordinate.
Definition geometry_type.hpp:35
Coord2D::x
T x
X coordinate.
Definition geometry_type.hpp:34
Coord3D::x
T x
X coordinate.
Definition geometry_type.hpp:44
Coord3D::y
T y
Y coordinate.
Definition geometry_type.hpp:45
DifficultySettings::line_reverse_mode
bool line_reverse_mode
reversing at stations or not
Definition settings_type.h:140
EngineInfo::cargo_age_period
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
Definition engine_type.h:214
EngineInfo::misc_flags
EngineMiscFlags misc_flags
Miscellaneous flags.
Definition engine_type.h:209
EngineInfo::callback_mask
VehicleCallbackMasks callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition engine_type.h:210
FindDepotData
Helper container to find a depot.
Definition pathfinder_type.h:38
FindDepotData::best_length
uint best_length
The distance towards the depot in penalty, or UINT_MAX if not found.
Definition pathfinder_type.h:40
FindDepotData::reverse
bool reverse
True if reversing is necessary for the train to get to this depot.
Definition pathfinder_type.h:41
FindDepotData::tile
TileIndex tile
The tile of the depot.
Definition pathfinder_type.h:39
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:155
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition newgrf.h:154
GUISettings::lost_vehicle_warn
bool lost_vehicle_warn
if a vehicle can't find its destination, show a warning
Definition settings_type.h:165
GUISettings::show_track_reservation
bool show_track_reservation
highlight reserved tracks.
Definition settings_type.h:220
GameSettings::pf
PathfinderSettings pf
settings for all pathfinders
Definition settings_type.h:639
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition settings_type.h:633
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition settings_type.h:641
GetNewVehiclePosResult
Position information of a vehicle after it moved.
Definition vehicle_func.h:214
GetNewVehiclePosResult::new_tile
TileIndex new_tile
Tile of the vehicle after moving.
Definition vehicle_func.h:217
GetNewVehiclePosResult::y
int y
x and y position of the vehicle after moving
Definition vehicle_func.h:215
GetNewVehiclePosResult::old_tile
TileIndex old_tile
Current tile of the vehicle.
Definition vehicle_func.h:216
GroundVehicleCache::cached_weight
uint32_t cached_weight
Total weight of the consist (valid only for the first engine).
Definition ground_vehicle.hpp:32
GroundVehicleCache::first_engine
EngineID first_engine
Cached EngineID of the front vehicle. EngineID::Invalid() for the front vehicle itself.
Definition ground_vehicle.hpp:44
GroundVehicleCache::cached_power
uint32_t cached_power
Total power of the consist (valid only for the first engine).
Definition ground_vehicle.hpp:39
GroundVehicleCache::cached_total_length
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
Definition ground_vehicle.hpp:43
GroundVehicleCache::cached_veh_length
uint8_t 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:45
GroundVehicleCache::cached_max_track_speed
uint16_t cached_max_track_speed
Maximum consist speed (in internal units) limited by track type (valid only for the first engine).
Definition ground_vehicle.hpp:38
GroundVehicle::IsChainInDepot
bool IsChainInDepot() const override
Check whether the whole vehicle chain is in the depot.
Definition ground_vehicle.cpp:190
GroundVehicle::SetFreeWagon
void SetFreeWagon()
Set a vehicle as a free wagon.
Definition ground_vehicle.hpp:291
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:234
GroundVehicle< Train, VEH_TRAIN >::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition ground_vehicle.hpp:83
GroundVehicle< Train, VEH_TRAIN >::CargoChanged
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Definition ground_vehicle.cpp:79
GroundVehicle::SetMultiheaded
void SetMultiheaded()
Set a vehicle as a multiheaded engine.
Definition ground_vehicle.hpp:301
GroundVehicle::IsEngine
bool IsEngine() const
Check if a vehicle is an engine (can be first in a consist).
Definition ground_vehicle.hpp:318
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition ground_vehicle.hpp:336
GroundVehicle::IsMultiheaded
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Definition ground_vehicle.hpp:330
GroundVehicle::SetEngine
void SetEngine()
Set engine status.
Definition ground_vehicle.hpp:281
GroundVehicle::SetWagon
void SetWagon()
Set a vehicle to be a wagon.
Definition ground_vehicle.hpp:271
GroundVehicle::SetFrontEngine
void SetFrontEngine()
Set front engine state.
Definition ground_vehicle.hpp:251
GroundVehicle::gv_flags
uint16_t gv_flags
Definition ground_vehicle.hpp:84
GroundVehicle::ClearFreeWagon
void ClearFreeWagon()
Clear a vehicle from being a free wagon.
Definition ground_vehicle.hpp:296
GroundVehicle::IsWagon
bool IsWagon() const
Check if a vehicle is a wagon.
Definition ground_vehicle.hpp:324
GroundVehicle::Crash
uint Crash(bool flooded) override
Common code executed for crashed ground vehicles.
Definition ground_vehicle.hpp:103
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:312
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:365
GroundVehicle< Train, VEH_TRAIN >::GetAcceleration
int GetAcceleration() const
Calculates the acceleration of the vehicle under its current conditions.
Definition ground_vehicle.cpp:105
GroundVehicle::ClearFrontEngine
void ClearFrontEngine()
Remove the front engine state.
Definition ground_vehicle.hpp:256
GroundVehicle::SetLastSpeed
void SetLastSpeed()
Update the GUI variant of the current speed of the vehicle.
Definition ground_vehicle.hpp:343
GroupStatistics::CountVehicle
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition group_cmd.cpp:152
Map::Size
static uint Size()
Get the size of the map.
Definition map_func.h:290
MutableSpriteCache::sprite_seq
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Definition vehicle_base.h:162
OrderBackup::Backup
static void Backup(const Vehicle *v, uint32_t user)
Create an order backup for the given vehicle.
Definition order_backup.cpp:84
Order
Definition order_base.h:33
Order::GetDepotOrderType
OrderDepotTypeFlags GetDepotOrderType() const
What caused us going to the depot?
Definition order_base.h:150
Order::GetMaxSpeed
uint16_t 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:207
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition order_base.h:99
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
Order::GetStopLocation
OrderStopLocation GetStopLocation() const
Where must we stop at the platform?
Definition order_base.h:148
Order::GetType
OrderType GetType() const
Get the type of order of this order.
Definition order_base.h:72
Order::MakeDummy
void MakeDummy()
Makes this order a Dummy order.
Definition order_cmd.cpp:116
Order::MakeGoToDepot
void MakeGoToDepot(DestinationID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=OrderNonStopFlag::NoIntermediate, OrderDepotActionFlags action={}, CargoType cargo=CARGO_NO_REFIT)
Makes this order a Go To Depot order.
Definition order_cmd.cpp:73
Order::SetDestination
void SetDestination(DestinationID destination)
Sets the destination of this order.
Definition order_base.h:106
Order::GetDepotActionType
OrderDepotActionFlags GetDepotActionType() const
What are we going to do when in the depot.
Definition order_base.h:152
Order::Free
void Free()
'Free' the order
Definition order_cmd.cpp:47
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:2176
Order::GetNonStopType
OrderNonStopFlags GetNonStopType() const
At which stations must we stop?
Definition order_base.h:146
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition tilearea_type.h:19
PBSTileInfo
This struct contains information about the end of a reserved path.
Definition pbs.h:26
PBSTileInfo::trackdir
Trackdir trackdir
The reserved trackdir on the tile.
Definition pbs.h:28
PBSTileInfo::tile
TileIndex tile
Tile the path ends, INVALID_TILE if no valid path was found.
Definition pbs.h:27
PBSTileInfo::okay
bool okay
True if tile is a safe waiting position, false otherwise.
Definition pbs.h:29
PathfinderSettings::path_backoff_interval
uint8_t path_backoff_interval
ticks between checks for a free path.
Definition settings_type.h:501
PathfinderSettings::wait_for_pbs_path
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
Definition settings_type.h:500
PathfinderSettings::wait_oneway_signal
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
Definition settings_type.h:496
PathfinderSettings::reserve_paths
bool reserve_paths
always reserve paths regardless of signal type.
Definition settings_type.h:499
PathfinderSettings::yapf
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
Definition settings_type.h:503
PathfinderSettings::reverse_at_signals
bool reverse_at_signals
whether to reverse at signals at all
Definition settings_type.h:495
PathfinderSettings::forbid_90_deg
bool forbid_90_deg
forbid trains to make 90 deg turns
Definition settings_type.h:493
PathfinderSettings::wait_twoway_signal
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
Definition settings_type.h:497
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF >
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem<&_vehicle_pool >::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
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:357
RailVehicleInfo
Information about a rail vehicle.
Definition engine_type.h:74
RailVehicleInfo::power
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition engine_type.h:82
RailVehicleInfo::user_def_data
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition engine_type.h:94
RailVehicleInfo::running_cost
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition engine_type.h:84
RailVehicleInfo::shorten_factor
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Definition engine_type.h:91
RailVehicleInfo::railtypes
RailTypes railtypes
Railtypes, mangled if elrail is disabled.
Definition engine_type.h:78
RailVehicleInfo::pow_wag_power
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition engine_type.h:88
RailVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition engine_type.h:81
RailVehicleInfo::capacity
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition engine_type.h:87
RailVehicleInfo::pow_wag_weight
uint8_t pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition engine_type.h:89
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition geometry_type.hpp:101
Rect::Width
int Width() const
Get width of Rect.
Definition geometry_type.hpp:111
Rect::Height
int Height() const
Get height of Rect.
Definition geometry_type.hpp:117
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition bitmath_func.hpp:277
SoundSettings::ambient
bool ambient
Play ambient, industry and town sounds.
Definition settings_type.h:279
SoundSettings::disaster
bool disaster
Play disaster and accident sounds.
Definition settings_type.h:277
SpecializedStation< Station, false >::Get
static Station * Get(auto index)
Gets station with given index.
Definition base_station_base.h:248
SpecializedVehicle::Next
T * Next() const
Get next vehicle in the chain.
Definition vehicle_base.h:1049
SpecializedVehicle::Iterate
static Pool::IterateWrapper< T > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
Definition vehicle_base.h:1203
SpecializedVehicle::Previous
T * Previous() const
Get previous vehicle in the chain.
Definition vehicle_base.h:1055
SpecializedVehicle::From
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition vehicle_base.h:1134
SpecializedVehicle::GetIfValid
static T * GetIfValid(auto index)
Returns vehicle if the index is a valid index for this vehicle type.
Definition vehicle_base.h:1124
SpecializedVehicle::First
T * First() const
Get the first vehicle in the chain.
Definition vehicle_base.h:1031
SpecializedVehicle::GetNextVehicle
T * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
Definition vehicle_base.h:1093
SpecializedVehicle::Get
static T * Get(auto index)
Gets vehicle with given index.
Definition vehicle_base.h:1115
SpecializedVehicle::UpdateViewport
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
Definition vehicle_base.h:1156
SpecializedVehicle::GetLastEnginePart
T * GetLastEnginePart()
Get the last part of an articulated engine.
Definition vehicle_base.h:1087
SpecializedVehicle::GetFirstEnginePart
T * GetFirstEnginePart()
Get the first part of an articulated engine.
Definition vehicle_base.h:1075
SpecializedVehicle::Last
T * Last()
Get the last vehicle in the chain.
Definition vehicle_base.h:1037
SpriteBounds::offset
Coord3D< int8_t > offset
Relative position of sprite from bounding box.
Definition sprite.h:21
SpriteBounds::origin
Coord3D< int8_t > origin
Position of northern corner within tile.
Definition sprite.h:19
SpriteBounds::extent
Coord3D< uint8_t > extent
Size of bounding box.
Definition sprite.h:20
Station
Station data structure.
Definition station_base.h:520
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:289
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
TrainCache::cached_max_curve_speed
uint16_t cached_max_curve_speed
max consist speed limited by curves
Definition train.h:83
TrainCache::cached_curve_speed_mod
int16_t cached_curve_speed_mod
curve speed modifier of the entire train
Definition train.h:82
TrainCache::cached_tilt
bool cached_tilt
train can tilt; feature provides a bonus in curves
Definition train.h:79
Train
'Train' is either a loco or a wagon.
Definition train.h:91
Train::PlayLeaveStationSound
void PlayLeaveStationSound(bool force=false) const override
Play a sound for a train leaving the station.
Definition train_cmd.cpp:2215
Train::UpdateAcceleration
void UpdateAcceleration()
Update acceleration of the train from the cached power and weight.
Definition train_cmd.cpp:430
Train::OnNewCalendarDay
void OnNewCalendarDay() override
Calendar day handler.
Definition train_cmd.cpp:4182
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:150
Train::GetVehicleTrackdir
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Definition train_cmd.cpp:4226
Train::GetImage
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const override
Get the sprite to display the train.
Definition train_cmd.cpp:494
Train::crash_anim_pos
uint16_t crash_anim_pos
Crash animation counter.
Definition train.h:93
Train::Tick
bool Tick() override
Update train vehicle data for a tick.
Definition train_cmd.cpp:4115
Train::ReserveTrackUnderConsist
void ReserveTrackUnderConsist() const
Tries to reserve track under whole train consist.
Definition train_cmd.cpp:3120
Train::GetOrderStationLocation
TileIndex GetOrderStationLocation(StationID station) override
Get the location of the next station to visit.
Definition train_cmd.cpp:2984
Train::GetDisplayImageWidth
int GetDisplayImageWidth(Point *offset=nullptr) const
Get the width of a train vehicle image in the GUI.
Definition train_cmd.cpp:460
Train::FindClosestDepot
ClosestDepot FindClosestDepot() override
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
Definition train_cmd.cpp:2206
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:1493
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:174
Train::GetMaxWeight
uint16_t GetMaxWeight() const override
Calculates the weight value that this vehicle will have when fully loaded with its current cargo.
Definition train_cmd.cpp:4243
Train::GetCurveSpeedLimit
uint16_t GetCurveSpeedLimit() const
Computes train speed limit caused by curves.
Definition train_cmd.cpp:307
Train::IsPrimaryVehicle
bool IsPrimaryVehicle() const override
Whether this is the primary vehicle in the chain.
Definition train.h:118
Train::MarkDirty
void MarkDirty() override
Goods at the consist have changed, update the graphics, cargo, and acceleration.
Definition train_cmd.cpp:2999
Train::UpdateSpeed
int UpdateSpeed()
This function looks at the vehicle and updates its speed (cur_speed and subspeed) variables.
Definition train_cmd.cpp:3019
Train::Crash
uint Crash(bool flooded=false) override
The train vehicle crashed! Update its status and other parts around it.
Definition train_cmd.cpp:3142
Train::GetAccelerationType
VehicleAccelerationModel GetAccelerationType() const
Allows to know the acceleration type of a vehicle.
Definition train.h:187
Train::GetAccelerationStatus
AccelStatus GetAccelerationStatus() const
Checks the current acceleration status of this vehicle.
Definition train.h:284
Train::OnNewEconomyDay
void OnNewEconomyDay() override
Economy day handler.
Definition train_cmd.cpp:4188
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition train_cmd.cpp:107
Train::GetRunningCost
Money GetRunningCost() const override
Get running cost for the train consist.
Definition train_cmd.cpp:4090
Train::wait_counter
uint16_t wait_counter
Ticks waiting in front of a signal, ticks being stuck or a counter for forced proceeding through sign...
Definition train.h:94
Train::GetCurrentMaxSpeed
int GetCurrentMaxSpeed() const override
Calculates the maximum speed of the vehicle under its current conditions.
Definition train_cmd.cpp:382
VehicleCache::cached_max_speed
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition vehicle_base.h:93
VehicleSettings::max_trains
UnitID max_trains
max trains in game per company
Definition settings_type.h:526
VehicleSettings::train_acceleration_model
uint8_t train_acceleration_model
realistic acceleration for trains
Definition settings_type.h:520
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition settings_type.h:524
VehicleSettings::freight_trains
uint8_t freight_trains
value to multiply the weight of cargo by
Definition settings_type.h:531
VehicleSettings::max_train_length
uint8_t max_train_length
maximum length for trains
Definition settings_type.h:518
VehicleSpriteSeq
Sprite sequence for a vehicle part.
Definition vehicle_base.h:102
VehicleSpriteSeq::IsValid
bool IsValid() const
Check whether the sequence contains any sprites.
Definition vehicle_base.h:114
VehicleSpriteSeq::GetBounds
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Definition vehicle.cpp:114
VehicleSpriteSeq::Set
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
Definition vehicle_base.h:130
VehicleSpriteSeq::Draw
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
Definition vehicle.cpp:142
Vehicle
Vehicle data structure.
Definition vehicle_base.h:205
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition vehicle_base.h:278
Vehicle::z_pos
int32_t z_pos
z coordinate.
Definition vehicle_base.h:267
Vehicle::direction
Direction direction
facing
Definition vehicle_base.h:268
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition vehicle.cpp:718
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
Vehicle::IsStoppedInDepot
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
Definition vehicle_base.h:515
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
Vehicle::LeaveStation
void LeaveStation()
Perform all actions when leaving a station.
Definition vehicle.cpp:2327
Vehicle::AddToShared
void AddToShared(Vehicle *shared_chain)
Adds this vehicle to a shared vehicle chain.
Definition vehicle.cpp:2956
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition vehicle_base.h:296
Vehicle::date_of_last_service
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
Definition vehicle_base.h:256
Vehicle::cargo_cap
uint16_t cargo_cap
total capacity
Definition vehicle_base.h:299
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:293
Vehicle::GetNumOrders
VehicleOrderID GetNumOrders() const
Get the number of orders this vehicle has.
Definition vehicle_base.h:705
Vehicle::random_bits
uint16_t random_bits
Bits used for randomized variational spritegroups.
Definition vehicle_base.h:290
Vehicle::ReleaseUnitNumber
void ReleaseUnitNumber()
Release the vehicle's unit number.
Definition vehicle.cpp:2396
Vehicle::day_counter
uint8_t day_counter
Increased by one for each day.
Definition vehicle_base.h:304
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:2407
Vehicle::profit_this_year
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition vehicle_base.h:234
Vehicle::colourmap
SpriteID colourmap
NOSAVE: cached colour mapping.
Definition vehicle_base.h:249
Vehicle::breakdown_ctr
uint8_t breakdown_ctr
Counter for managing breakdown events.
Definition vehicle_base.h:260
Vehicle::GetAdvanceDistance
uint GetAdvanceDistance()
Determines the vehicle "progress" needed for moving a step.
Definition vehicle_base.h:412
Vehicle::group_id
GroupID group_id
Index of group Pool array.
Definition vehicle_base.h:321
Vehicle::vehstatus
VehStates vehstatus
Status.
Definition vehicle_base.h:309
Vehicle::date_of_last_service_newgrf
TimerGameCalendar::Date date_of_last_service_newgrf
Last calendar date the vehicle had a service at a depot, unchanged by the date cheat to protect again...
Definition vehicle_base.h:257
Vehicle::subspeed
uint8_t subspeed
fractional speed
Definition vehicle_base.h:284
Vehicle::IsArticulatedPart
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
Definition vehicle_base.h:922
Vehicle::LeaveUnbunchingDepot
void LeaveUnbunchingDepot()
Leave an unbunching depot and calculate the next departure time for shared order vehicles.
Definition vehicle.cpp:2486
Vehicle::cargo_type
CargoType cargo_type
type of cargo this vehicle is carrying
Definition vehicle_base.h:297
Vehicle::acceleration
uint8_t acceleration
used by train & aircraft
Definition vehicle_base.h:285
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition vehicle_base.h:311
Vehicle::HandlePathfindingResult
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Definition vehicle.cpp:762
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition vehicle_base.h:587
Vehicle::y_pos
int32_t y_pos
y coordinate.
Definition vehicle_base.h:266
Vehicle::x_pos
int32_t x_pos
x coordinate.
Definition vehicle_base.h:265
Vehicle::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
Definition vehicle.cpp:728
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition vehicle_base.h:314
Vehicle::value
Money value
Value of the vehicle.
Definition vehicle_base.h:236
Vehicle::refit_cap
uint16_t refit_cap
Capacity left over from before last refit.
Definition vehicle_base.h:300
Vehicle::InvalidateNewGRFCache
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
Definition vehicle_base.h:450
Vehicle::vcache
VehicleCache vcache
Cache of often used vehicle values.
Definition vehicle_base.h:319
Vehicle::GetGRFID
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
Definition vehicle.cpp:738
Vehicle::bounds
SpriteBounds bounds
Bounding box of vehicle.
Definition vehicle_base.h:277
Vehicle::BeginLoading
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
Definition vehicle.cpp:2183
Vehicle::spritenum
uint8_t spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
Definition vehicle_base.h:276
Vehicle::cur_speed
uint16_t cur_speed
current speed
Definition vehicle_base.h:283
Vehicle::cargo_subtype
uint8_t cargo_subtype
Used for livery refits (NewGRF variations)
Definition vehicle_base.h:298
Vehicle::IsFrontEngine
bool IsFrontEngine() const
Check if the vehicle is a front engine.
Definition vehicle_base.h:913
Vehicle::IsWaitingForUnbunching
bool IsWaitingForUnbunching() const
Check whether a vehicle inside a depot is waiting for unbunching.
Definition vehicle.cpp:2533
Vehicle::fill_percent_te_id
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition vehicle_base.h:280
Vehicle::SetNext
void SetNext(Vehicle *next)
Set the next vehicle of this vehicle.
Definition vehicle.cpp:2927
Vehicle::max_age
TimerGameCalendar::Date max_age
Maximum age.
Definition vehicle_base.h:255
Vehicle::sprite_cache
MutableSpriteCache sprite_cache
Cache of sprites and values related to recalculating them, see MutableSpriteCache.
Definition vehicle_base.h:323
Vehicle::reliability
uint16_t reliability
Reliability.
Definition vehicle_base.h:258
Vehicle::HandleBreakdown
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds,...
Definition vehicle.cpp:1332
Vehicle::progress
uint8_t progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
Definition vehicle_base.h:287
Vehicle::reliability_spd_dec
uint16_t reliability_spd_dec
Reliability decrease speed.
Definition vehicle_base.h:259
Vehicle::tick_counter
uint8_t tick_counter
Increased by one for each tick.
Definition vehicle_base.h:305
Vehicle::tile
TileIndex tile
Current tile index.
Definition vehicle_base.h:225
Vehicle::dest_tile
TileIndex dest_tile
Heading for this tile.
Definition vehicle_base.h:232
Vehicle::CopyVehicleConfigAndStatistics
void CopyVehicleConfigAndStatistics(Vehicle *src)
Copy certain configurations and statistics of a vehicle after successful autoreplace/renew The functi...
Definition vehicle_base.h:733
Vehicle::UpdatePosition
void UpdatePosition()
Update the position of the vehicle.
Definition vehicle.cpp:1662
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition vehicle_base.h:292
Vehicle::ShowVisualEffect
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Definition vehicle.cpp:2777
Vehicle::build_year
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Definition vehicle_base.h:252
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition vehicle_base.h:270
Vehicle::unitnumber
UnitID unitnumber
unit number, for display purposes only
Definition vehicle_base.h:281
Vehicle::NeedsAutomaticServicing
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
Definition vehicle.cpp:283
Vehicle::running_ticks
uint8_t running_ticks
Number of ticks this vehicle was not stopped this day.
Definition vehicle_base.h:306
YAPFSettings::maximum_go_to_depot_penalty
uint32_t maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
Definition settings_type.h:455
VehicleEnterTileState::EnteredStation
@ EnteredStation
The vehicle entered a station.
VehicleEnterTileState::CannotEnter
@ CannotEnter
The vehicle cannot enter the tile.
VehicleEnterTileState::EnteredWormhole
@ EnteredWormhole
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
VehicleEnterTile
VehicleEnterTileStates VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
Definition vehicle.cpp:1819
IsTileType
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
INVALID_TILE
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:95
TILE_SIZE
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
MP_STATION
@ MP_STATION
A tile of a station.
Definition tile_type.h:53
MP_TUNNELBRIDGE
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition tile_type.h:57
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition tile_type.h:49
timer_game_calendar.h
Definition of the game-calendar-timer.
timer_game_economy.h
Definition of the game-economy-timer.
RemoveFirstTrackdir
Trackdir RemoveFirstTrackdir(TrackdirBits *trackdirs)
Removes first Trackdir from TrackdirBits and returns it.
Definition track_func.h:156
TrackdirToTrack
Track TrackdirToTrack(Trackdir trackdir)
Returns the Track that a given Trackdir represents.
Definition track_func.h:262
TrackToTrackBits
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition track_func.h:77
TrackBitsToTrackdirBits
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:319
VehicleExitDir
DiagDirection VehicleExitDir(Direction direction, TrackBits track)
Determine the side in which the vehicle will leave the tile.
Definition track_func.h:714
TrackStatusToTrackdirBits
TrackdirBits TrackStatusToTrackdirBits(TrackStatus ts)
Returns the present-trackdir-information of a TrackStatus.
Definition track_func.h:352
TrackBitsToTrack
Track TrackBitsToTrack(TrackBits tracks)
Converts TrackBits to Track.
Definition track_func.h:193
ReverseTrackdir
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:247
TracksOverlap
bool TracksOverlap(TrackBits bits)
Checks if the given tracks overlap, ie form a crossing.
Definition track_func.h:645
TrackDirectionToTrackdir
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:498
IsValidTrackdir
bool IsValidTrackdir(Trackdir trackdir)
Checks if a Trackdir is valid for non-road vehicles.
Definition track_func.h:52
FindFirstTrackdir
Trackdir FindFirstTrackdir(TrackdirBits trackdirs)
Returns first Trackdir from TrackdirBits or INVALID_TRACKDIR.
Definition track_func.h:211
TrackdirReachesTrackdirs
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:584
DiagdirReachesTrackdirs
TrackdirBits DiagdirReachesTrackdirs(DiagDirection diagdir)
Returns all trackdirs that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:555
FindFirstTrack
Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
Definition track_func.h:177
TrackEnterdirToTrackdir
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:486
DiagdirReachesTracks
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:573
DiagDirToDiagTrackBits
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition track_func.h:524
DiagDirToDiagTrackdir
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:537
TrackStatusToRedSignals
TrackdirBits TrackStatusToRedSignals(TrackStatus ts)
Returns the red-signal-information of a TrackStatus.
Definition track_func.h:376
TrackdirToExitdir
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:439
DiagDirToDiagTrack
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track incidating with that diagdir.
Definition track_func.h:512
TrackdirBitsToTrackBits
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:308
TrackBits
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
TRACK_BIT_WORMHOLE
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Definition track_type.h:52
TRACK_BIT_UPPER
@ TRACK_BIT_UPPER
Upper track.
Definition track_type.h:39
TRACK_BIT_DEPOT
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Definition track_type.h:53
TRACK_BIT_LEFT
@ TRACK_BIT_LEFT
Left track.
Definition track_type.h:41
TRACK_BIT_Y
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition track_type.h:36
TRACK_BIT_X
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
TRACK_BIT_MASK
@ TRACK_BIT_MASK
Bitmask for the first 6 bits.
Definition track_type.h:51
TRACK_BIT_LOWER
@ TRACK_BIT_LOWER
Lower track.
Definition track_type.h:40
TRACK_BIT_RIGHT
@ TRACK_BIT_RIGHT
Right track.
Definition track_type.h:42
Trackdir
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:66
INVALID_TRACKDIR
@ INVALID_TRACKDIR
Flag for an invalid trackdir.
Definition track_type.h:85
TrackdirBits
TrackdirBits
Allow incrementing of Trackdir variables.
Definition track_type.h:97
TRACKDIR_BIT_NONE
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:98
Track
Track
These are used to specify a single track.
Definition track_type.h:19
INVALID_TRACK
@ INVALID_TRACK
Flag for an invalid track.
Definition track_type.h:28
TRACK_Y
@ TRACK_Y
Track along the y-axis (north-west to south-east)
Definition track_type.h:22
TRACK_BEGIN
@ TRACK_BEGIN
Used for iterations.
Definition track_type.h:20
TRACK_X
@ TRACK_X
Track along the x-axis (north-east to south-west)
Definition track_type.h:21
ConsistChangeFlag::Capacity
@ Capacity
Allow vehicles to change capacity.
ConsistChangeFlag::Length
@ Length
Allow vehicles to change length.
CCF_TRACK
static constexpr ConsistChangeFlags CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition train.h:52
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition train_cmd.cpp:2419
Reversed
@ Reversed
Used for vehicle var 0xFE bit 8 (toggled each time the train is reversed, accurate for first vehicle ...
Definition train.h:31
AllowedOnNormalRail
@ AllowedOnNormalRail
Electric train engine is allowed to run on normal rail. *‍/.
Definition train.h:30
Stuck
@ Stuck
Train can't get a path reservation.
Definition train.h:32
Flipped
@ Flipped
Reverse the visible direction of the vehicle.
Definition train.h:28
PoweredWagon
@ PoweredWagon
Wagon is powered.
Definition train.h:27
LeavingStation
@ LeavingStation
Train is just leaving a station.
Definition train.h:33
Reversing
@ Reversing
Train is slowing down to reverse.
Definition train.h:26
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:263
TrainForceProceeding
TrainForceProceeding
Modes for ignoring signals.
Definition train.h:38
TFP_SIGNAL
@ TFP_SIGNAL
Ignore next signal, after the signal ignore being stuck.
Definition train.h:41
TFP_NONE
@ TFP_NONE
Normal operation.
Definition train.h:39
TFP_STUCK
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:40
CCF_ARRANGE
static constexpr ConsistChangeFlags CCF_ARRANGE
Valid changes for arranging the consist in a depot.
Definition train.h:56
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:3091
CmdBuildRailWagon
static CommandCost CmdBuildRailWagon(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad wagon.
Definition train_cmd.cpp:639
NormaliseTrainHead
static void NormaliseTrainHead(Train *head)
Normalise the head of the train again, i.e.
Definition train_cmd.cpp:1191
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:1130
CheckTrainStayInDepot
static bool CheckTrainStayInDepot(Train *v)
Will the train stay in the depot the next tick?
Definition train_cmd.cpp:2296
FindClosestTrainDepot
static FindDepotData FindClosestTrainDepot(Train *v, int max_distance)
Try to find a depot nearby.
Definition train_cmd.cpp:2199
CmdForceTrainProceed
CommandCost CmdForceTrainProceed(DoCommandFlags flags, VehicleID veh_id)
Force a train through a red signal.
Definition train_cmd.cpp:2170
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:1791
CheckTrainCollision
static uint CheckTrainCollision(Vehicle *v, Train *t)
Collision test function.
Definition train_cmd.cpp:3205
MakeTrainBackup
static void MakeTrainBackup(TrainList &list, Train *t)
Make a backup of a train into a train list.
Definition train_cmd.cpp:875
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:2234
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:1150
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:2899
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:2626
_breakdown_speeds
static const uint16_t _breakdown_speeds[16]
Maximum speeds for train that is broken down or approaching line end.
Definition train_cmd.cpp:3781
TrainApproachingLineEnd
static bool TrainApproachingLineEnd(Train *v, bool signal, bool reverse)
Train is approaching line end, slow down and possibly reverse.
Definition train_cmd.cpp:3794
InsertInConsist
static void InsertInConsist(Train *dst, Train *chain)
Inserts a chain into the train at dst.
Definition train_cmd.cpp:924
UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval
void UpdateAdjacentLevelCrossingTilesOnLevelCrossingRemoval(TileIndex tile, Axis road_axis)
Update adjacent level crossing tiles in this multi-track crossing, due to removal of a level crossing...
Definition train_cmd.cpp:1840
SwapTrainFlags
static void SwapTrainFlags(uint16_t *swap_flag1, uint16_t *swap_flag2)
Swap the two up/down flags in two ways:
Definition train_cmd.cpp:1584
UpdateLevelCrossingTile
static void UpdateLevelCrossingTile(TileIndex tile, bool sound, bool force_barred)
Sets a level crossing tile to the correct state.
Definition train_cmd.cpp:1769
HandleCrashedTrain
static bool HandleCrashedTrain(Train *v)
Handle a crashed train.
Definition train_cmd.cpp:3742
NormalizeTrainVehInDepot
void NormalizeTrainVehInDepot(const Train *u)
Move all free vehicles in the depot to the train.
Definition train_cmd.cpp:717
CmdReverseTrainDirection
CommandCost CmdReverseTrainDirection(DoCommandFlags flags, VehicleID veh_id, bool reverse_single_veh)
Reverse train.
Definition train_cmd.cpp:2076
CheckLevelCrossing
static bool CheckLevelCrossing(TileIndex tile)
Check if a level crossing should be barred.
Definition train_cmd.cpp:1756
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:992
AdvanceWagonsBeforeSwap
static void AdvanceWagonsBeforeSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition train_cmd.cpp:1892
CmdBuildRailVehicle
CommandCost CmdBuildRailVehicle(DoCommandFlags flags, TileIndex tile, const Engine *e, Vehicle **ret)
Build a railroad vehicle.
Definition train_cmd.cpp:773
AdvanceWagonsAfterSwap
static void AdvanceWagonsAfterSwap(Train *v)
Advances wagons for train reversing, needed for variable length wagons.
Definition train_cmd.cpp:1920
FreightWagonMult
uint8_t FreightWagonMult(CargoType cargo)
Return the cargo weight multiplier to use for a rail vehicle.
Definition train_cmd.cpp:68
TrainCheckIfLineEnds
static bool TrainCheckIfLineEnds(Train *v, bool reverse=true)
Checks for line end.
Definition train_cmd.cpp:3896
ReverseTrainDirection
void ReverseTrainDirection(Train *v)
Turn a train around.
Definition train_cmd.cpp:1985
FreeTrainTrackReservation
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
Definition train_cmd.cpp:2419
TrainCrashed
static uint TrainCrashed(Train *v)
Marks train as crashed and creates an AI event.
Definition train_cmd.cpp:3181
NormaliseDualHeads
static void NormaliseDualHeads(Train *t)
Normalise the dual heads in the train, i.e.
Definition train_cmd.cpp:938
CheckTrainAttachment
static CommandCost CheckTrainAttachment(Train *t)
Check whether the train parts can be attached.
Definition train_cmd.cpp:1016
_accel_slowdown
static const AccelerationSlowdownParams _accel_slowdown[]
Speed update fractions for each acceleration type.
Definition train_cmd.cpp:3079
CmdMoveRailVehicle
CommandCost CmdMoveRailVehicle(DoCommandFlags flags, VehicleID src_veh, VehicleID dest_veh, bool move_chain)
Move a rail vehicle around inside the depot.
Definition train_cmd.cpp:1221
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:2502
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:2378
IsTrain
static bool IsTrain(const Vehicle *v)
Check if the vehicle is a train.
Definition train_cmd.cpp:1691
CheckTrainsLengths
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition train_cmd.cpp:75
MaybeBarCrossingWithSound
static void MaybeBarCrossingWithSound(TileIndex tile)
Bars crossing and plays ding-ding sound if not barred already.
Definition train_cmd.cpp:1878
TrainOnCrossing
bool TrainOnCrossing(TileIndex tile)
Check if a level crossing tile has a train on it.
Definition train_cmd.cpp:1702
ChangeTrainDirRandomly
static void ChangeTrainDirRandomly(Train *v)
Rotate all vehicles of a (crashed) train chain randomly to animate the crash.
Definition train_cmd.cpp:3714
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:1823
NormaliseSubtypes
static void NormaliseSubtypes(Train *chain)
Normalise the sub types of the parts in this chain.
Definition train_cmd.cpp:960
TrainController
bool TrainController(Train *v, Vehicle *nomove, bool reverse=true)
Move a vehicle chain one movement stop forwards.
Definition train_cmd.cpp:3289
CmdSellRailWagon
CommandCost CmdSellRailWagon(DoCommandFlags flags, Vehicle *t, bool sell_chain, bool backup_order, ClientID user)
Sell a (single) train wagon/engine.
Definition train_cmd.cpp:1419
TrainApproachingCrossingTile
static TileIndex TrainApproachingCrossingTile(const Train *v)
Determines whether train is approaching a rail-road crossing (thus making it barred)
Definition train_cmd.cpp:3869
DetermineNextTrainForceProceeding
static TrainForceProceeding DetermineNextTrainForceProceeding(const Train *t)
Determine to what force_proceed should be changed.
Definition train_cmd.cpp:2153
RemoveFromConsist
static void RemoveFromConsist(Train *part, bool chain=false)
Remove the given wagon from its consist.
Definition train_cmd.cpp:907
RestoreTrainBackup
static void RestoreTrainBackup(TrainList &list)
Restore the train from the backup list.
Definition train_cmd.cpp:884
DeleteLastWagon
static void DeleteLastWagon(Train *v)
Deletes/Clears the last wagon of a crashed train.
Definition train_cmd.cpp:3635
TrainCanLeaveTile
static bool TrainCanLeaveTile(const Train *v)
Determines whether train would like to leave the tile.
Definition train_cmd.cpp:3839
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:263
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:3036
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:1560
TrainApproachingCrossing
static bool TrainApproachingCrossing(TileIndex tile)
Finds a vehicle approaching rail-road crossing.
Definition train_cmd.cpp:1732
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:1649
ExtendTrainReservation
static PBSTileInfo ExtendTrainReservation(const Train *v, TrackBits *new_tracks, DiagDirection *enterdir)
Extend a train path as far as possible.
Definition train_cmd.cpp:2513
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:582
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:4144
TrainList
std::vector< Train * > TrainList
Helper type for lists/vectors of trains.
Definition train_cmd.cpp:868
TrainApproachingCrossingEnum
static bool TrainApproachingCrossingEnum(const Vehicle *v, TileIndex tile)
Checks if a train is approaching a rail-road crossing.
Definition train_cmd.cpp:1715
UpdateStatusAfterSwap
static void UpdateStatusAfterSwap(Train *v)
Updates some variables after swapping the vehicle.
Definition train_cmd.cpp:1612
GetFreeWagonsInDepot
static std::vector< VehicleID > GetFreeWagonsInDepot(TileIndex tile)
Get a list of free wagons in a depot.
Definition train_cmd.cpp:614
train_cmd.h
Command definitions related to trains.
train_sprites.h
Sprites to use for trains.
TRANSPORT_RAIL
@ TRANSPORT_RAIL
Transport by train.
Definition transport_type.h:25
IsTunnel
bool IsTunnel(Tile t)
Is this a tunnel (entrance)?
Definition tunnel_map.h:23
MarkBridgeDirty
void MarkBridgeDirty(TileIndex begin, TileIndex end, DiagDirection direction, uint bridge_height)
Mark bridge tiles dirty.
Definition tunnelbridge_cmd.cpp:64
GetTunnelBridgeDirection
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
Definition tunnelbridge_map.h:26
GetOtherTunnelBridgeEnd
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
Definition tunnelbridge_map.h:78
SetTunnelBridgeReservation
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
Definition tunnelbridge_map.h:104
ShowNewGrfVehicleError
void ShowNewGrfVehicleError(EngineID engine, StringID part1, StringID part2, GRFBug bug_type, bool critical)
Displays a "NewGrf Bug" error message for a engine, and pauses the game if not networking.
Definition vehicle.cpp:328
VehicleEnterDepot
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it,...
Definition vehicle.cpp:1520
GetFreeUnitNumber
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
Definition vehicle.cpp:1876
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:354
VehicleServiceInDepot
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
Definition vehicle.cpp:178
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:1765
DecreaseVehicleValue
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
Definition vehicle.cpp:1270
EconomyAgeVehicle
void EconomyAgeVehicle(Vehicle *v)
Update economy age of a vehicle.
Definition vehicle.cpp:1398
TunnelBridgeIsFree
CommandCost TunnelBridgeIsFree(TileIndex tile, TileIndex endtile, const Vehicle *ignore)
Finds vehicle in tunnel / bridge.
Definition vehicle.cpp:551
AgeVehicle
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
Definition vehicle.cpp:1410
VehState::Crashed
@ Crashed
Vehicle is crashed.
VehState::TrainSlowing
@ TrainSlowing
Train is slowing down.
VehState::Hidden
@ Hidden
Vehicle is not visible.
VehState::DefaultPalette
@ DefaultPalette
Use default vehicle palette.
VehState::Stopped
@ Stopped
Vehicle is stopped by the player.
vehicle_func.h
Functions related to vehicles.
CUSTOM_VEHICLE_SPRITENUM_REVERSED
@ CUSTOM_VEHICLE_SPRITENUM_REVERSED
Vehicle sprite from NewGRF with reverse driving direction (from articulation callback)
Definition vehicle_func.h:29
HasVehicleOnTile
bool HasVehicleOnTile(TileIndex tile, UnaryPred &&predicate)
Loop over vehicles on a tile, and check whether a predicate is true for any of them.
Definition vehicle_func.h:106
VIWD_CONSIST_CHANGED
@ VIWD_CONSIST_CHANGED
Vehicle composition was changed.
Definition vehicle_gui.h:37
EngineImageType
EngineImageType
Visualisation contexts of vehicles and engines.
Definition vehicle_type.h:74
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition vehicle_type.h:25
VEHICLE_LENGTH
static const uint VEHICLE_LENGTH
The length of a vehicle in tile units.
Definition vehicle_type.h:65
WID_VV_REFIT
@ WID_VV_REFIT
Open the refit window.
Definition vehicle_widget.h:22
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
viewport_func.h
Functions related to (drawing on) viewports.
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1195
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition window.cpp:3205
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:3297
SetWindowWidgetDirty
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
Definition window.cpp:3192
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3179
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:3314
WC_VEHICLE_ORDERS
@ WC_VEHICLE_ORDERS
Vehicle orders; Window numbers:
Definition window_type.h:217
WC_VEHICLE_DEPOT
@ WC_VEHICLE_DEPOT
Depot view; Window numbers:
Definition window_type.h:356
WC_TRAINS_LIST
@ WC_TRAINS_LIST
Trains list; Window numbers:
Definition window_type.h:313
WC_VEHICLE_REFIT
@ WC_VEHICLE_REFIT
Vehicle refit; Window numbers:
Definition window_type.h:211
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition window_type.h:205
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition window_type.h:374
WC_VEHICLE_VIEW
@ WC_VEHICLE_VIEW
Vehicle view; Window numbers:
Definition window_type.h:344
WC_VEHICLE_TIMETABLE
@ WC_VEHICLE_TIMETABLE
Vehicle timetable; Window numbers:
Definition window_type.h:229
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:642
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:655
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:589
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:580
yapf.hpp
Base includes/functions for YAPF.
zoom_func.h
Functions related to zooming.
ScaleSpriteTrad
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107
UnScaleGUI
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77