OpenTTD Source: src/train_cmd.cpp Source File

OpenTTD Source 14.0-beta1

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