OpenTTD: src/roadveh_cmd.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

roadveh_cmd.cpp
Go to the documentation of this file.
1 /* $Id: roadveh_cmd.cpp 27190 2015-03-16 20:01:14Z frosch $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include "roadveh.h"
14 #include "command_func.h"
15 #include "news_func.h"
16 #include "pathfinder/npf/npf_func.h"
17 #include "station_base.h"
18 #include "company_func.h"
19 #include "articulated_vehicles.h"
20 #include "newgrf_sound.h"
21 #include "pathfinder/yapf/yapf.h"
22 #include "strings_func.h"
23 #include "tunnelbridge_map.h"
24 #include "date_func.h"
25 #include "vehicle_func.h"
26 #include "sound_func.h"
27 #include "ai/ai.hpp"
28 #include "game/game.hpp"
29 #include "depot_map.h"
30 #include "effectvehicle_func.h"
31 #include "roadstop_base.h"
32 #include "spritecache.h"
33 #include "core/random_func.hpp"
34 #include "company_base.h"
35 #include "core/backup_type.hpp"
36 #include "newgrf.h"
37 #include "zoom_func.h"
38
39 #include "table/strings.h"
40
41 #include "safeguards.h"
42
43 static const uint16 _roadveh_images[] = {
44 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
45 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
46 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
47 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
48 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
49 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
50 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
51 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
52 };
53
54 static const uint16 _roadveh_full_adder[] = {
55 0, 88, 0, 0, 0, 0, 48, 48,
56 48, 48, 0, 0, 64, 64, 0, 16,
57 16, 0, 88, 0, 0, 0, 0, 48,
58 48, 48, 48, 0, 0, 64, 64, 0,
59 16, 16, 0, 88, 0, 0, 0, 0,
60 48, 48, 48, 48, 0, 0, 64, 64,
61 0, 16, 16, 0, 8, 8, 8, 8,
62 0, 0, 0, 8, 8, 8, 8
63 };
64 assert_compile(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
65
66 template <>
67 bool IsValidImageIndex<VEH_ROAD>(uint8 image_index)
68 {
69 return image_index < lengthof(_roadveh_images);
70 }
71
73 static const TrackdirBits _road_enter_dir_to_reachable_trackdirs[DIAGDIR_END] = {
74 TRACKDIR_BIT_LEFT_N | TRACKDIR_BIT_LOWER_E | TRACKDIR_BIT_X_NE, // Enter from north east
75 TRACKDIR_BIT_LEFT_S | TRACKDIR_BIT_UPPER_E | TRACKDIR_BIT_Y_SE, // Enter from south east
76 TRACKDIR_BIT_UPPER_W | TRACKDIR_BIT_X_SW | TRACKDIR_BIT_RIGHT_S, // Enter from south west
77 TRACKDIR_BIT_RIGHT_N | TRACKDIR_BIT_LOWER_W | TRACKDIR_BIT_Y_NW // Enter from north west
78 };
79
80 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
81 TRACKDIR_RVREV_NE, TRACKDIR_RVREV_SE, TRACKDIR_RVREV_SW, TRACKDIR_RVREV_NW
82 };
83
85 static const Trackdir _roadveh_depot_exit_trackdir[DIAGDIR_END] = {
86 TRACKDIR_X_NE, TRACKDIR_Y_SE, TRACKDIR_X_SW, TRACKDIR_Y_NW
87 };
88
89
94 bool RoadVehicle::IsBus() const
95 {
96 assert(this->IsFrontEngine());
97 return IsCargoInClass(this->cargo_type, CC_PASSENGERS);
98 }
99
105 int RoadVehicle::GetDisplayImageWidth(Point *offset) const
106 {
107 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
108
109 if (offset != NULL) {
110 offset->x = ScaleGUITrad(reference_width) / 2;
111 offset->y = 0;
112 }
113 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
114 }
115
116 static SpriteID GetRoadVehIcon(EngineID engine, EngineImageType image_type)
117 {
118 const Engine *e = Engine::Get(engine);
119 uint8 spritenum = e->u.road.image_index;
120
121 if (is_custom_sprite(spritenum)) {
122 SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
123 if (sprite != 0) return sprite;
124
125 spritenum = e->original_image_index;
126 }
127
128 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
129 return DIR_W + _roadveh_images[spritenum];
130 }
131
132 SpriteID RoadVehicle::GetImage(Direction direction, EngineImageType image_type) const
133 {
134 uint8 spritenum = this->spritenum;
135 SpriteID sprite;
136
137 if (is_custom_sprite(spritenum)) {
138 sprite = GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type);
139 if (sprite != 0) return sprite;
140
141 spritenum = this->GetEngine()->original_image_index;
142 }
143
144 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
145 sprite = direction + _roadveh_images[spritenum];
146
147 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
148
149 return sprite;
150 }
151
161 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
162 {
163 SpriteID sprite = GetRoadVehIcon(engine, image_type);
164 const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
165 preferred_x = Clamp(preferred_x,
166 left - UnScaleGUI(real_sprite->x_offs),
167 right - UnScaleGUI(real_sprite->width) - UnScaleGUI(real_sprite->x_offs));
168 DrawSprite(sprite, pal, preferred_x, y);
169 }
170
180 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
181 {
182 const Sprite *spr = GetSprite(GetRoadVehIcon(engine, image_type), ST_NORMAL);
183
184 width = UnScaleGUI(spr->width);
185 height = UnScaleGUI(spr->height);
186 xoffs = UnScaleGUI(spr->x_offs);
187 yoffs = UnScaleGUI(spr->y_offs);
188 }
189
195 static uint GetRoadVehLength(const RoadVehicle *v)
196 {
197 const Engine *e = v->GetEngine();
198 uint length = VEHICLE_LENGTH;
199
200 uint16 veh_len = CALLBACK_FAILED;
201 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
202 /* Use callback 36 */
203 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
204 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
205 } else {
206 /* Use callback 11 */
207 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
208 }
209 if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
210 if (veh_len != 0) {
211 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
212 }
213
214 return length;
215 }
216
223 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
224 {
225 assert(v->type == VEH_ROAD);
226 assert(v->IsFrontEngine());
227
228 v->InvalidateNewGRFCacheOfChain();
229
230 v->gcache.cached_total_length = 0;
231
232 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
233 /* Check the v->first cache. */
234 assert(u->First() == v);
235
236 /* Update the 'first engine' */
237 u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
238
239 /* Update the length of the vehicle. */
240 uint veh_len = GetRoadVehLength(u);
241 /* Verify length hasn't changed. */
242 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
243
244 u->gcache.cached_veh_length = veh_len;
245 v->gcache.cached_total_length += u->gcache.cached_veh_length;
246
247 /* Update visual effect */
248 u->UpdateVisualEffect();
249
250 /* Update cargo aging period. */
251 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
252 }
253
254 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
255 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
256 }
257
267 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
268 {
269 if (HasTileRoadType(tile, ROADTYPE_TRAM) != HasBit(e->info.misc_flags, EF_ROAD_TRAM)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
270
271 if (flags & DC_EXEC) {
272 const RoadVehicleInfo *rvi = &e->u.road;
273
274 RoadVehicle *v = new RoadVehicle();
275 *ret = v;
276 v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
277 v->owner = _current_company;
278
279 v->tile = tile;
280 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
281 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
282 v->x_pos = x;
283 v->y_pos = y;
284 v->z_pos = GetSlopePixelZ(x, y);
285
286 v->state = RVSB_IN_DEPOT;
287 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
288
289 v->spritenum = rvi->image_index;
290 v->cargo_type = e->GetDefaultCargoType();
291 v->cargo_cap = rvi->capacity;
292 v->refit_cap = 0;
293
294 v->last_station_visited = INVALID_STATION;
295 v->last_loading_station = INVALID_STATION;
296 v->engine_type = e->index;
297 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
298
299 v->reliability = e->reliability;
300 v->reliability_spd_dec = e->reliability_spd_dec;
301 v->max_age = e->GetLifeLengthInDays();
302 _new_vehicle_id = v->index;
303
304 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
305
306 v->date_of_last_service = _date;
307 v->build_year = _cur_year;
308
309 v->cur_image = SPR_IMG_QUERY;
310 v->random_bits = VehicleRandomBits();
311 v->SetFrontEngine();
312
313 v->roadtype = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
314 v->compatible_roadtypes = RoadTypeToRoadTypes(v->roadtype);
315 v->gcache.cached_veh_length = VEHICLE_LENGTH;
316
317 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
318 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
319
320 AddArticulatedParts(v);
321 v->InvalidateNewGRFCacheOfChain();
322
323 /* Call various callbacks after the whole consist has been constructed */
324 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
325 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
326 u->refit_cap = 0;
327 v->InvalidateNewGRFCache();
328 u->InvalidateNewGRFCache();
329 }
330 RoadVehUpdateCache(v);
331 /* Initialize cached values for realistic acceleration. */
332 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) v->CargoChanged();
333
334 v->UpdatePosition();
335
336 CheckConsistencyOfArticulatedVehicle(v);
337 }
338
339 return CommandCost();
340 }
341
342 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
343 {
344 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
345
346 switch (_settings_game.pf.pathfinder_for_roadvehs) {
347 case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
348 case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
349
350 default: NOT_REACHED();
351 }
352 }
353
354 bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
355 {
356 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
357 if (rfdd.best_length == UINT_MAX) return false;
358
359 if (location != NULL) *location = rfdd.tile;
360 if (destination != NULL) *destination = GetDepotIndex(rfdd.tile);
361
362 return true;
363 }
364
374 CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
375 {
376 RoadVehicle *v = RoadVehicle::GetIfValid(p1);
377 if (v == NULL) return CMD_ERROR;
378
379 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
380
381 CommandCost ret = CheckOwnership(v->owner);
382 if (ret.Failed()) return ret;
383
384 if ((v->vehstatus & VS_STOPPED) ||
385 (v->vehstatus & VS_CRASHED) ||
386 v->breakdown_ctr != 0 ||
387 v->overtaking != 0 ||
388 v->state == RVSB_WORMHOLE ||
389 v->IsInDepot() ||
390 v->current_order.IsType(OT_LOADING)) {
391 return CMD_ERROR;
392 }
393
394 if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
395
396 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && DirToDiagDir(v->direction) == GetTunnelBridgeDirection(v->tile)) return CMD_ERROR;
397
398 if (flags & DC_EXEC) v->reverse_ctr = 180;
399
400 return CommandCost();
401 }
402
403
404 void RoadVehicle::MarkDirty()
405 {
406 for (RoadVehicle *v = this; v != NULL; v = v->Next()) {
407 v->colourmap = PAL_NONE;
408 v->UpdateViewport(true, false);
409 }
410 this->CargoChanged();
411 }
412
413 void RoadVehicle::UpdateDeltaXY(Direction direction)
414 {
415 static const int8 _delta_xy_table[8][10] = {
416 /* y_extent, x_extent, y_offs, x_offs, y_bb_offs, x_bb_offs, y_extent_shorten, x_extent_shorten, y_bb_offs_shorten, x_bb_offs_shorten */
417 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
418 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
419 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
420 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
421 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
422 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
423 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
424 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
425 };
426
427 int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
428 if (!IsDiagonalDirection(direction)) shorten >>= 1;
429
430 const int8 *bb = _delta_xy_table[direction];
431 this->x_bb_offs = bb[5] + bb[9] * shorten;
432 this->y_bb_offs = bb[4] + bb[8] * shorten;;
433 this->x_offs = bb[3];
434 this->y_offs = bb[2];
435 this->x_extent = bb[1] + bb[7] * shorten;
436 this->y_extent = bb[0] + bb[6] * shorten;
437 this->z_extent = 6;
438 }
439
444 inline int RoadVehicle::GetCurrentMaxSpeed() const
445 {
446 int max_speed = this->vcache.cached_max_speed;
447
448 /* Limit speed to 50% while reversing, 75% in curves. */
449 for (const RoadVehicle *u = this; u != NULL; u = u->Next()) {
450 if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
451 if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) {
452 max_speed = this->vcache.cached_max_speed / 2;
453 break;
454 } else if ((u->direction & 1) == 0) {
455 max_speed = this->vcache.cached_max_speed * 3 / 4;
456 }
457 }
458
459 /* Vehicle is on the middle part of a bridge. */
460 if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
461 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
462 }
463 }
464
465 return min(max_speed, this->current_order.GetMaxSpeed() * 2);
466 }
467
472 static void DeleteLastRoadVeh(RoadVehicle *v)
473 {
474 RoadVehicle *first = v->First();
475 Vehicle *u = v;
476 for (; v->Next() != NULL; v = v->Next()) u = v;
477 u->SetNext(NULL);
478 v->last_station_visited = first->last_station_visited; // for PreDestructor
479
480 /* Only leave the road stop when we're really gone. */
481 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
482
483 delete v;
484 }
485
486 static void RoadVehSetRandomDirection(RoadVehicle *v)
487 {
488 static const DirDiff delta[] = {
489 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
490 };
491
492 do {
493 uint32 r = Random();
494
495 v->direction = ChangeDir(v->direction, delta[r & 3]);
496 v->UpdateViewport(true, true);
497 } while ((v = v->Next()) != NULL);
498 }
499
505 static bool RoadVehIsCrashed(RoadVehicle *v)
506 {
507 v->crashed_ctr++;
508 if (v->crashed_ctr == 2) {
509 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
510 } else if (v->crashed_ctr <= 45) {
511 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
512 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
513 bool ret = v->Next() != NULL;
514 DeleteLastRoadVeh(v);
515 return ret;
516 }
517
518 return true;
519 }
520
527 static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
528 {
529 const Vehicle *u = (Vehicle*)data;
530
531 return (v->type == VEH_TRAIN &&
532 abs(v->z_pos - u->z_pos) <= 6 &&
533 abs(v->x_pos - u->x_pos) <= 4 &&
534 abs(v->y_pos - u->y_pos) <= 4) ? v : NULL;
535 }
536
537 uint RoadVehicle::Crash(bool flooded)
538 {
539 uint pass = this->GroundVehicleBase::Crash(flooded);
540 if (this->IsFrontEngine()) {
541 pass += 1; // driver
542
543 /* If we're in a drive through road stop we ought to leave it */
544 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
545 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
546 }
547 }
548 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
549 return pass;
550 }
551
552 static void RoadVehCrash(RoadVehicle *v)
553 {
554 uint pass = v->Crash();
555
556 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
557 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
558
559 SetDParam(0, pass);
560 AddVehicleNewsItem(
561 (pass == 1) ?
562 STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH,
563 NT_ACCIDENT,
564 v->index
565 );
566
567 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
568 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
569 }
570
571 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
572 {
573 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
574 if (u->state == RVSB_WORMHOLE) continue;
575
576 TileIndex tile = u->tile;
577
578 if (!IsLevelCrossingTile(tile)) continue;
579
580 if (HasVehicleOnPosXY(v->x_pos, v->y_pos, u, EnumCheckRoadVehCrashTrain)) {
581 RoadVehCrash(v);
582 return true;
583 }
584 }
585
586 return false;
587 }
588
589 TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
590 {
591 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
592
593 const Station *st = Station::Get(station);
594 if (!CanVehicleUseStation(this, st)) {
595 /* There is no stop left at the station, so don't even TRY to go there */
596 this->IncrementRealOrderIndex();
597 return 0;
598 }
599
600 return st->xy;
601 }
602
603 static void StartRoadVehSound(const RoadVehicle *v)
604 {
605 if (!PlayVehicleSound(v, VSE_START)) {
606 SoundID s = RoadVehInfo(v->engine_type)->sfx;
607 if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0) {
608 s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
609 }
610 SndPlayVehicleFx(s, v);
611 }
612 }
613
614 struct RoadVehFindData {
615 int x;
616 int y;
617 const Vehicle *veh;
618 Vehicle *best;
619 uint best_diff;
620 Direction dir;
621 };
622
623 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
624 {
625 static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
626 static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
627
628 RoadVehFindData *rvf = (RoadVehFindData*)data;
629
630 short x_diff = v->x_pos - rvf->x;
631 short y_diff = v->y_pos - rvf->y;
632
633 if (v->type == VEH_ROAD &&
634 !v->IsInDepot() &&
635 abs(v->z_pos - rvf->veh->z_pos) < 6 &&
636 v->direction == rvf->dir &&
637 rvf->veh->First() != v->First() &&
638 (dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
639 (dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
640 (dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
641 (dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
642 uint diff = abs(x_diff) + abs(y_diff);
643
644 if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
645 rvf->best = v;
646 rvf->best_diff = diff;
647 }
648 }
649
650 return NULL;
651 }
652
653 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
654 {
655 RoadVehFindData rvf;
656 RoadVehicle *front = v->First();
657
658 if (front->reverse_ctr != 0) return NULL;
659
660 rvf.x = x;
661 rvf.y = y;
662 rvf.dir = dir;
663 rvf.veh = v;
664 rvf.best_diff = UINT_MAX;
665
666 if (front->state == RVSB_WORMHOLE) {
667 FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
668 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
669 } else {
670 FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
671 }
672
673 /* This code protects a roadvehicle from being blocked for ever
674 * If more than 1480 / 74 days a road vehicle is blocked, it will
675 * drive just through it. The ultimate backup-code of TTD.
676 * It can be disabled. */
677 if (rvf.best_diff == UINT_MAX) {
678 front->blocked_ctr = 0;
679 return NULL;
680 }
681
682 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return NULL;
683
684 return RoadVehicle::From(rvf.best);
685 }
686
692 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
693 {
694 if (v->IsBus()) {
695 /* Check if station was ever visited before */
696 if (!(st->had_vehicle_of_type & HVOT_BUS)) {
697 st->had_vehicle_of_type |= HVOT_BUS;
698 SetDParam(0, st->index);
699 AddVehicleNewsItem(
700 v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
701 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
702 v->index,
703 st->index
704 );
705 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
706 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
707 }
708 } else {
709 /* Check if station was ever visited before */
710 if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
711 st->had_vehicle_of_type |= HVOT_TRUCK;
712 SetDParam(0, st->index);
713 AddVehicleNewsItem(
714 v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
715 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
716 v->index,
717 st->index
718 );
719 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
720 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
721 }
722 }
723 }
724
732 int RoadVehicle::UpdateSpeed()
733 {
734 switch (_settings_game.vehicle.roadveh_acceleration_model) {
735 default: NOT_REACHED();
736 case AM_ORIGINAL:
737 return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
738
739 case AM_REALISTIC:
740 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
741 }
742 }
743
744 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
745 {
746 static const Direction _roadveh_new_dir[] = {
747 DIR_N , DIR_NW, DIR_W , INVALID_DIR,
748 DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
749 DIR_E , DIR_SE, DIR_S
750 };
751
752 x = x - v->x_pos + 1;
753 y = y - v->y_pos + 1;
754
755 if ((uint)x > 2 || (uint)y > 2) return v->direction;
756 return _roadveh_new_dir[y * 4 + x];
757 }
758
759 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
760 {
761 Direction new_dir = RoadVehGetNewDirection(v, x, y);
762 Direction old_dir = v->direction;
763 DirDiff delta;
764
765 if (new_dir == old_dir) return old_dir;
766 delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
767 return ChangeDir(old_dir, delta);
768 }
769
770 struct OvertakeData {
771 const RoadVehicle *u;
772 const RoadVehicle *v;
773 TileIndex tile;
774 Trackdir trackdir;
775 };
776
777 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
778 {
779 const OvertakeData *od = (OvertakeData*)data;
780
781 return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : NULL;
782 }
783
790 static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
791 {
792 TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->compatible_roadtypes);
793 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
794 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
795 TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
796
797 /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
798 if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
799
800 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
801 return HasVehicleOnPos(od->tile, od, EnumFindVehBlockingOvertake);
802 }
803
804 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
805 {
806 OvertakeData od;
807
808 od.v = v;
809 od.u = u;
810
811 /* Trams can't overtake other trams */
812 if (v->roadtype == ROADTYPE_TRAM) return;
813
814 /* Don't overtake in stations */
815 if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
816
817 /* For now, articulated road vehicles can't overtake anything. */
818 if (v->HasArticulatedPart()) return;
819
820 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
821 if (v->direction != u->direction || !(v->direction & 1)) return;
822
823 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
824 if (v->state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir((Trackdir)(v->state & RVSB_TRACKDIR_MASK))) return;
825
826 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
827 * accelerating, take the maximum speed for the comparison, else the current speed.
828 * Original acceleration always accelerates, so always use the maximum speed. */
829 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
830 if (u_speed >= v->GetCurrentMaxSpeed() &&
831 !(u->vehstatus & VS_STOPPED) &&
832 u->cur_speed != 0) {
833 return;
834 }
835
836 od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
837
838 /* Are the current and the next tile suitable for overtaking?
839 * - Does the track continue along od.trackdir
840 * - No junctions
841 * - No barred levelcrossing
842 * - No other vehicles in the way
843 */
844 od.tile = v->tile;
845 if (CheckRoadBlockedForOvertaking(&od)) return;
846
847 od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
848 if (CheckRoadBlockedForOvertaking(&od)) return;
849
850 /* When the vehicle in front of us is stopped we may only take
851 * half the time to pass it than when the vehicle is moving. */
852 v->overtaking_ctr = (od.u->cur_speed == 0 || (od.u->vehstatus & VS_STOPPED)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
853 v->overtaking = RVSB_DRIVE_SIDE;
854 }
855
856 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
857 {
858 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
859
860 if (old_z < v->z_pos) {
861 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
862 } else {
863 uint16 spd = v->cur_speed + 2;
864 if (spd <= v->vcache.cached_max_speed) v->cur_speed = spd;
865 }
866 }
867
868 static int PickRandomBit(uint bits)
869 {
870 uint i;
871 uint num = RandomRange(CountBits(bits));
872
873 for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
874 return i;
875 }
876
885 static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
886 {
887 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
888
889 TileIndex desttile;
890 Trackdir best_track;
891 bool path_found = true;
892
893 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->compatible_roadtypes);
894 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
895 TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
896
897 if (IsTileType(tile, MP_ROAD)) {
898 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir || (GetRoadTypes(tile) & v->compatible_roadtypes) == 0)) {
899 /* Road depot owned by another company or with the wrong orientation */
900 trackdirs = TRACKDIR_BIT_NONE;
901 }
902 } else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
903 /* Standard road stop (drive-through stops are treated as normal road) */
904
905 if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
906 /* different station owner or wrong orientation or the vehicle has articulated parts */
907 trackdirs = TRACKDIR_BIT_NONE;
908 } else {
909 /* Our station */
910 RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
911
912 if (GetRoadStopType(tile) != rstype) {
913 /* Wrong station type */
914 trackdirs = TRACKDIR_BIT_NONE;
915 } else {
916 /* Proper station type, check if there is free loading bay */
917 if (!_settings_game.pf.roadveh_queue && IsStandardRoadStopTile(tile) &&
918 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
919 /* Station is full and RV queuing is off */
920 trackdirs = TRACKDIR_BIT_NONE;
921 }
922 }
923 }
924 }
925 /* The above lookups should be moved to GetTileTrackStatus in the
926 * future, but that requires more changes to the pathfinder and other
927 * stuff, probably even more arguments to GTTS.
928 */
929
930 /* Remove tracks unreachable from the enter dir */
931 trackdirs &= _road_enter_dir_to_reachable_trackdirs[enterdir];
932 if (trackdirs == TRACKDIR_BIT_NONE) {
933 /* No reachable tracks, so we'll reverse */
934 return_track(_road_reverse_table[enterdir]);
935 }
936
937 if (v->reverse_ctr != 0) {
938 bool reverse = true;
939 if (v->roadtype == ROADTYPE_TRAM) {
940 /* Trams may only reverse on a tile if it contains at least the straight
941 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
942 RoadBits rb = GetAnyRoadBits(tile, ROADTYPE_TRAM);
943 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
944 reverse = ((rb & straight) == straight) ||
945 (rb == DiagDirToRoadBits(enterdir));
946 }
947 if (reverse) {
948 v->reverse_ctr = 0;
949 if (v->tile != tile) {
950 return_track(_road_reverse_table[enterdir]);
951 }
952 }
953 }
954
955 desttile = v->dest_tile;
956 if (desttile == 0) {
957 /* We've got no destination, pick a random track */
958 return_track(PickRandomBit(trackdirs));
959 }
960
961 /* Only one track to choose between? */
962 if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
963 return_track(FindFirstBit2x64(trackdirs));
964 }
965
966 switch (_settings_game.pf.pathfinder_for_roadvehs) {
967 case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
968 case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
969
970 default: NOT_REACHED();
971 }
972 v->HandlePathfindingResult(path_found);
973
974 found_best_track:;
975
976 if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
977
978 return best_track;
979 }
980
981 struct RoadDriveEntry {
982 byte x, y;
983 };
984
985 #include "table/roadveh_movement.h"
986
987 static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
988 {
989 /* Don't leave unless v and following wagons are in the depot. */
990 for (const RoadVehicle *u = v; u != NULL; u = u->Next()) {
991 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
992 }
993
994 DiagDirection dir = GetRoadDepotDirection(v->tile);
995 v->direction = DiagDirToDir(dir);
996
997 Trackdir tdir = _roadveh_depot_exit_trackdir[dir];
998 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
999
1000 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1001 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1002
1003 if (first) {
1004 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1005 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1006 VehicleEnterDepot(v);
1007 return true;
1008 }
1009
1010 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != NULL) return true;
1011
1012 VehicleServiceInDepot(v);
1013
1014 StartRoadVehSound(v);
1015
1016 /* Vehicle is about to leave a depot */
1017 v->cur_speed = 0;
1018 }
1019
1020 v->vehstatus &= ~VS_HIDDEN;
1021 v->state = tdir;
1022 v->frame = RVC_DEPOT_START_FRAME;
1023
1024 v->x_pos = x;
1025 v->y_pos = y;
1026 v->UpdatePosition();
1027 v->UpdateInclination(true, true);
1028
1029 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1030
1031 return true;
1032 }
1033
1034 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1035 {
1036 if (prev->tile == v->tile && !already_reversed) {
1037 /* If the previous vehicle is on the same tile as this vehicle is
1038 * then it must have reversed. */
1039 return _road_reverse_table[entry_dir];
1040 }
1041
1042 byte prev_state = prev->state;
1043 Trackdir dir;
1044
1045 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1046 DiagDirection diag_dir = INVALID_DIAGDIR;
1047
1048 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1049 diag_dir = GetTunnelBridgeDirection(tile);
1050 } else if (IsRoadDepotTile(tile)) {
1051 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1052 }
1053
1054 if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1055 dir = DiagDirToDiagTrackdir(diag_dir);
1056 } else {
1057 if (already_reversed && prev->tile != tile) {
1058 /*
1059 * The vehicle has reversed, but did not go straight back.
1060 * It immediately turn onto another tile. This means that
1061 * the roadstate of the previous vehicle cannot be used
1062 * as the direction we have to go with this vehicle.
1063 *
1064 * Next table is build in the following way:
1065 * - first row for when the vehicle in front went to the northern or
1066 * western tile, second for southern and eastern.
1067 * - columns represent the entry direction.
1068 * - cell values are determined by the Trackdir one has to take from
1069 * the entry dir (column) to the tile in north or south by only
1070 * going over the trackdirs used for turning 90 degrees, i.e.
1071 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1072 */
1073 static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1074 { TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N, TRACKDIR_UPPER_E },
1075 { TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }};
1076 dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1077 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1078 dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1079 } else if (prev_state < TRACKDIR_END) {
1080 dir = (Trackdir)prev_state;
1081 } else {
1082 return INVALID_TRACKDIR;
1083 }
1084 }
1085
1086 /* Do some sanity checking. */
1087 static const RoadBits required_roadbits[] = {
1088 ROAD_X, ROAD_Y, ROAD_NW | ROAD_NE, ROAD_SW | ROAD_SE,
1089 ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1090 };
1091 RoadBits required = required_roadbits[dir & 0x07];
1092
1093 if ((required & GetAnyRoadBits(tile, v->roadtype, true)) == ROAD_NONE) {
1094 dir = INVALID_TRACKDIR;
1095 }
1096
1097 return dir;
1098 }
1099
1107 static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadBits r)
1108 {
1109 /* The 'current' company is not necessarily the owner of the vehicle. */
1110 Backup<CompanyByte> cur_company(_current_company, c, FILE_LINE);
1111
1112 CommandCost ret = DoCommand(t, ROADTYPE_TRAM << 4 | r, 0, DC_NO_WATER, CMD_BUILD_ROAD);
1113
1114 cur_company.Restore();
1115 return ret.Succeeded();
1116 }
1117
1118 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1119 {
1120 if (v->overtaking != 0) {
1121 if (IsTileType(v->tile, MP_STATION)) {
1122 /* Force us to be not overtaking! */
1123 v->overtaking = 0;
1124 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1125 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1126 * if the vehicle started a corner. To protect that, only allow an abort of
1127 * overtake if we are on straight roads */
1128 if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->state)) {
1129 v->overtaking = 0;
1130 }
1131 }
1132 }
1133
1134 /* If this vehicle is in a depot and we've reached this point it must be
1135 * one of the articulated parts. It will stay in the depot until activated
1136 * by the previous vehicle in the chain when it gets to the right place. */
1137 if (v->IsInDepot()) return true;
1138
1139 if (v->state == RVSB_WORMHOLE) {
1140 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1141 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
1142
1143 if (v->IsFrontEngine()) {
1144 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1145 if (u != NULL) {
1146 v->cur_speed = u->First()->cur_speed;
1147 return false;
1148 }
1149 }
1150
1151 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
1152 /* Vehicle has just entered a bridge or tunnel */
1153 v->x_pos = gp.x;
1154 v->y_pos = gp.y;
1155 v->UpdatePosition();
1156 v->UpdateInclination(true, true);
1157 return true;
1158 }
1159
1160 v->x_pos = gp.x;
1161 v->y_pos = gp.y;
1162 v->UpdatePosition();
1163 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
1164 return true;
1165 }
1166
1167 /* Get move position data for next frame.
1168 * For a drive-through road stop use 'straight road' move data.
1169 * In this case v->state is masked to give the road stop entry direction. */
1170 RoadDriveEntry rd = _road_drive_data[v->roadtype][(
1171 (HasBit(v->state, RVS_IN_DT_ROAD_STOP) ? v->state & RVSB_ROAD_STOP_TRACKDIR_MASK : v->state) +
1172 (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1173
1174 if (rd.x & RDE_NEXT_TILE) {
1175 TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1176 Trackdir dir;
1177
1178 if (v->IsFrontEngine()) {
1179 /* If this is the front engine, look for the right path. */
1180 dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1181 } else {
1182 dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1183 }
1184
1185 if (dir == INVALID_TRACKDIR) {
1186 if (!v->IsFrontEngine()) error("Disconnecting road vehicle.");
1187 v->cur_speed = 0;
1188 return false;
1189 }
1190
1191 again:
1192 uint start_frame = RVC_DEFAULT_START_FRAME;
1193 if (IsReversingRoadTrackdir(dir)) {
1194 /* When turning around we can't be overtaking. */
1195 v->overtaking = 0;
1196
1197 /* Turning around */
1198 if (v->roadtype == ROADTYPE_TRAM) {
1199 /* Determine the road bits the tram needs to be able to turn around
1200 * using the 'big' corner loop. */
1201 RoadBits needed;
1202 switch (dir) {
1203 default: NOT_REACHED();
1204 case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1205 case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1206 case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1207 case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1208 }
1209 if ((v->Previous() != NULL && v->Previous()->tile == tile) ||
1210 (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1211 (needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE)) {
1212 /*
1213 * Taking the 'big' corner for trams only happens when:
1214 * - The previous vehicle in this (articulated) tram chain is
1215 * already on the 'next' tile, we just follow them regardless of
1216 * anything. When it is NOT on the 'next' tile, the tram started
1217 * doing a reversing turn when the piece of tram track on the next
1218 * tile did not exist yet. Do not use the big tram loop as that is
1219 * going to cause the tram to split up.
1220 * - Or the front of the tram can drive over the next tile.
1221 */
1222 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
1223 /*
1224 * Taking the 'small' corner for trams only happens when:
1225 * - We are not the from vehicle of an articulated tram.
1226 * - Or when the company cannot build on the next tile.
1227 *
1228 * The 'small' corner means that the vehicle is on the end of a
1229 * tram track and needs to start turning there. To do this properly
1230 * the tram needs to start at an offset in the tram turning 'code'
1231 * for 'big' corners. It furthermore does not go to the next tile,
1232 * so that needs to be fixed too.
1233 */
1234 tile = v->tile;
1235 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1236 } else {
1237 /* The company can build on the next tile, so wait till (s)he does. */
1238 v->cur_speed = 0;
1239 return false;
1240 }
1241 } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1242 v->cur_speed = 0;
1243 return false;
1244 } else {
1245 tile = v->tile;
1246 }
1247 }
1248
1249 /* Get position data for first frame on the new tile */
1250 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1251
1252 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1253 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1254
1255 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1256 if (v->IsFrontEngine()) {
1257 Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1258 if (u != NULL) {
1259 v->cur_speed = u->First()->cur_speed;
1260 return false;
1261 }
1262 }
1263
1264 uint32 r = VehicleEnterTile(v, tile, x, y);
1265 if (HasBit(r, VETS_CANNOT_ENTER)) {
1266 if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1267 v->cur_speed = 0;
1268 return false;
1269 }
1270 /* Try an about turn to re-enter the previous tile */
1271 dir = _road_reverse_table[rd.x & 3];
1272 goto again;
1273 }
1274
1275 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1276 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1277 /* New direction is trying to turn vehicle around.
1278 * We can't turn at the exit of a road stop so wait.*/
1279 v->cur_speed = 0;
1280 return false;
1281 }
1282
1283 /* If we are a drive through road stop and the next tile is of
1284 * the same road stop and the next tile isn't this one (i.e. we
1285 * are not reversing), then keep the reservation and state.
1286 * This way we will not be shortly unregister from the road
1287 * stop. It also makes it possible to load when on the edge of
1288 * two road stops; otherwise you could get vehicles that should
1289 * be loading but are not actually loading. */
1290 if (IsDriveThroughStopTile(v->tile) &&
1291 RoadStop::IsDriveThroughRoadStopContinuation(v->tile, tile) &&
1292 v->tile != tile) {
1293 /* So, keep 'our' state */
1294 dir = (Trackdir)v->state;
1295 } else if (IsRoadStop(v->tile)) {
1296 /* We're not continuing our drive through road stop, so leave. */
1297 RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
1298 }
1299 }
1300
1301 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1302 v->tile = tile;
1303 v->state = (byte)dir;
1304 v->frame = start_frame;
1305 }
1306 if (new_dir != v->direction) {
1307 v->direction = new_dir;
1308 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1309 }
1310 v->x_pos = x;
1311 v->y_pos = y;
1312 v->UpdatePosition();
1313 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1314 return true;
1315 }
1316
1317 if (rd.x & RDE_TURNED) {
1318 /* Vehicle has finished turning around, it will now head back onto the same tile */
1319 Trackdir dir;
1320 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1321
1322 if (v->roadtype == ROADTYPE_TRAM && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, ROADTYPE_TRAM, true))) {
1323 /*
1324 * The tram is turning around with one tram 'roadbit'. This means that
1325 * it is using the 'big' corner 'drive data'. However, to support the
1326 * trams to take a small corner, there is a 'turned' marker in the middle
1327 * of the turning 'drive data'. When the tram took the long corner, we
1328 * will still use the 'big' corner drive data, but we advance it one
1329 * frame. We furthermore set the driving direction so the turning is
1330 * going to be properly shown.
1331 */
1332 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1333 switch (rd.x & 0x3) {
1334 default: NOT_REACHED();
1335 case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1336 case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1337 case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1338 case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1339 }
1340 } else {
1341 if (v->IsFrontEngine()) {
1342 /* If this is the front engine, look for the right path. */
1343 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1344 } else {
1345 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1346 }
1347 }
1348
1349 if (dir == INVALID_TRACKDIR) {
1350 v->cur_speed = 0;
1351 return false;
1352 }
1353
1354 const RoadDriveEntry *rdp = _road_drive_data[v->roadtype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1355
1356 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1357 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1358
1359 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1360 if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != NULL) return false;
1361
1362 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1363 if (HasBit(r, VETS_CANNOT_ENTER)) {
1364 v->cur_speed = 0;
1365 return false;
1366 }
1367
1368 v->state = dir;
1369 v->frame = turn_around_start_frame;
1370
1371 if (new_dir != v->direction) {
1372 v->direction = new_dir;
1373 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1374 }
1375
1376 v->x_pos = x;
1377 v->y_pos = y;
1378 v->UpdatePosition();
1379 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1380 return true;
1381 }
1382
1383 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1384 * it's on a depot tile, check if it's time to activate the next vehicle in
1385 * the chain yet. */
1386 if (v->Next() != NULL && IsRoadDepotTile(v->tile)) {
1387 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1388 RoadVehLeaveDepot(v->Next(), false);
1389 }
1390 }
1391
1392 /* Calculate new position for the vehicle */
1393 int x = (v->x_pos & ~15) + (rd.x & 15);
1394 int y = (v->y_pos & ~15) + (rd.y & 15);
1395
1396 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1397
1398 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1399 /* Vehicle is not in a road stop.
1400 * Check for another vehicle to overtake */
1401 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1402
1403 if (u != NULL) {
1404 u = u->First();
1405 /* There is a vehicle in front overtake it if possible */
1406 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1407 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1408
1409 /* In case an RV is stopped in a road stop, why not try to load? */
1410 if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1411 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1412 v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1413 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK)) {
1414 Station *st = Station::GetByTile(v->tile);
1415 v->last_station_visited = st->index;
1416 RoadVehArrivesAt(v, st);
1417 v->BeginLoading();
1418 }
1419 return false;
1420 }
1421 }
1422
1423 Direction old_dir = v->direction;
1424 if (new_dir != old_dir) {
1425 v->direction = new_dir;
1426 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1427
1428 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1429 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1430 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1431 * The short (inner) curve has 8 frames, this elongates it to 10. */
1432 v->UpdateInclination(false, true);
1433 return true;
1434 }
1435
1436 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1437 * if the vehicle is in a drive-through road stop and this is the destination station
1438 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1439 * (the station test and stop type test ensure that other vehicles, using the road stop as
1440 * a through route, do not stop) */
1441 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1442 _road_stop_stop_frame[v->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)] == v->frame) ||
1443 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1444 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1445 v->owner == GetTileOwner(v->tile) &&
1446 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
1447 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1448
1449 RoadStop *rs = RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile));
1450 Station *st = Station::GetByTile(v->tile);
1451
1452 /* Vehicle is at the stop position (at a bay) in a road stop.
1453 * Note, if vehicle is loading/unloading it has already been handled,
1454 * so if we get here the vehicle has just arrived or is just ready to leave. */
1455 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1456 /* Vehicle has arrived at a bay in a road stop */
1457
1458 if (IsDriveThroughStopTile(v->tile)) {
1459 TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
1460
1461 /* Check if next inline bay is free and has compatible road. */
1462 if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && (GetRoadTypes(next_tile) & v->compatible_roadtypes) != 0) {
1463 v->frame++;
1464 v->x_pos = x;
1465 v->y_pos = y;
1466 v->UpdatePosition();
1467 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1468 return true;
1469 }
1470 }
1471
1472 rs->SetEntranceBusy(false);
1473 SetBit(v->state, RVS_ENTERED_STOP);
1474
1475 v->last_station_visited = st->index;
1476
1477 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1478 RoadVehArrivesAt(v, st);
1479 v->BeginLoading();
1480 return false;
1481 }
1482 } else {
1483 /* Vehicle is ready to leave a bay in a road stop */
1484 if (rs->IsEntranceBusy()) {
1485 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1486 v->cur_speed = 0;
1487 return false;
1488 }
1489 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1490 }
1491
1492 if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1493
1494 StartRoadVehSound(v);
1495 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1496 }
1497
1498 /* Check tile position conditions - i.e. stop position in depot,
1499 * entry onto bridge or into tunnel */
1500 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1501 if (HasBit(r, VETS_CANNOT_ENTER)) {
1502 v->cur_speed = 0;
1503 return false;
1504 }
1505
1506 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1507 v->current_order.Free();
1508 }
1509
1510 /* Move to next frame unless vehicle arrived at a stop position
1511 * in a depot or entered a tunnel/bridge */
1512 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1513 v->x_pos = x;
1514 v->y_pos = y;
1515 v->UpdatePosition();
1516 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1517 return true;
1518 }
1519
1520 static bool RoadVehController(RoadVehicle *v)
1521 {
1522 /* decrease counters */
1523 v->current_order_time++;
1524 if (v->reverse_ctr != 0) v->reverse_ctr--;
1525
1526 /* handle crashed */
1527 if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1528 return RoadVehIsCrashed(v);
1529 }
1530
1531 /* road vehicle has broken down? */
1532 if (v->HandleBreakdown()) return true;
1533 if (v->vehstatus & VS_STOPPED) return true;
1534
1535 ProcessOrders(v);
1536 v->HandleLoading();
1537
1538 if (v->current_order.IsType(OT_LOADING)) return true;
1539
1540 if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return true;
1541
1542 v->ShowVisualEffect();
1543
1544 /* Check how far the vehicle needs to proceed */
1545 int j = v->UpdateSpeed();
1546
1547 int adv_spd = v->GetAdvanceDistance();
1548 bool blocked = false;
1549 while (j >= adv_spd) {
1550 j -= adv_spd;
1551
1552 RoadVehicle *u = v;
1553 for (RoadVehicle *prev = NULL; u != NULL; prev = u, u = u->Next()) {
1554 if (!IndividualRoadVehicleController(u, prev)) {
1555 blocked = true;
1556 break;
1557 }
1558 }
1559 if (blocked) break;
1560
1561 /* Determine distance to next map position */
1562 adv_spd = v->GetAdvanceDistance();
1563
1564 /* Test for a collision, but only if another movement will occur. */
1565 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1566 }
1567
1568 v->SetLastSpeed();
1569
1570 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
1571 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
1572
1573 u->UpdateViewport(false, false);
1574 }
1575
1576 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1577 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1578 * on next tick to discover whether it is still blocked. */
1579 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1580
1581 return true;
1582 }
1583
1584 Money RoadVehicle::GetRunningCost() const
1585 {
1586 const Engine *e = this->GetEngine();
1587 if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1588
1589 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1590 if (cost_factor == 0) return 0;
1591
1592 return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1593 }
1594
1595 bool RoadVehicle::Tick()
1596 {
1597 this->tick_counter++;
1598
1599 if (this->IsFrontEngine()) {
1600 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1601 return RoadVehController(this);
1602 }
1603
1604 return true;
1605 }
1606
1607 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1608 {
1609 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1610 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1611 if (v->IsChainInDepot()) {
1612 VehicleServiceInDepot(v);
1613 return;
1614 }
1615
1616 uint max_penalty;
1617 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1618 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1619 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1620 default: NOT_REACHED();
1621 }
1622
1623 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1624 /* Only go to the depot if it is not too far out of our way. */
1625 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1626 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1627 /* If we were already heading for a depot but it has
1628 * suddenly moved farther away, we continue our normal
1629 * schedule? */
1630 v->current_order.MakeDummy();
1631 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1632 }
1633 return;
1634 }
1635
1636 DepotID depot = GetDepotIndex(rfdd.tile);
1637
1638 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1639 v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS &&
1640 !Chance16(1, 20)) {
1641 return;
1642 }
1643
1644 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1645 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
1646 v->dest_tile = rfdd.tile;
1647 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1648 }
1649
1650 void RoadVehicle::OnNewDay()
1651 {
1652 AgeVehicle(this);
1653
1654 if (!this->IsFrontEngine()) return;
1655
1656 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1657 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1658
1659 CheckIfRoadVehNeedsService(this);
1660
1661 CheckOrders(this);
1662
1663 if (this->running_ticks == 0) return;
1664
1665 CommandCost cost(EXPENSES_ROADVEH_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
1666
1667 this->profit_this_year -= cost.GetCost();
1668 this->running_ticks = 0;
1669
1670 SubtractMoneyFromCompanyFract(this->owner, cost);
1671
1672 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
1673 SetWindowClassesDirty(WC_ROADVEH_LIST);
1674 }
1675
1676 Trackdir RoadVehicle::GetVehicleTrackdir() const
1677 {
1678 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1679
1680 if (this->IsInDepot()) {
1681 /* We'll assume the road vehicle is facing outwards */
1682 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1683 }
1684
1685 if (IsStandardRoadStopTile(this->tile)) {
1686 /* We'll assume the road vehicle is facing outwards */
1687 return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1688 }
1689
1690 /* Drive through road stops / wormholes (tunnels) */
1691 if (this->state > RVSB_TRACKDIR_MASK) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
1692
1693 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1694 * otherwise transform it into a valid track direction */
1695 return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);
1696 }