Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / roadveh_cmd.cpp
blob6aace6b3e9f699a8dd405968d7419f3fce45cb34
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 */
8 /** @file roadveh_cmd.cpp Handling of road vehicles. */
10 #include "stdafx.h"
11 #include "roadveh.h"
12 #include "command_func.h"
13 #include "error_func.h"
14 #include "news_func.h"
15 #include "pathfinder/npf/npf_func.h"
16 #include "station_base.h"
17 #include "company_func.h"
18 #include "articulated_vehicles.h"
19 #include "newgrf_sound.h"
20 #include "pathfinder/yapf/yapf.h"
21 #include "strings_func.h"
22 #include "tunnelbridge_map.h"
23 #include "timer/timer_game_calendar.h"
24 #include "timer/timer_game_economy.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 #include "framerate_type.h"
39 #include "roadveh_cmd.h"
40 #include "road_cmd.h"
42 #include "table/strings.h"
44 #include "safeguards.h"
46 static const uint16_t _roadveh_images[] = {
47 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
48 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
49 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
50 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
51 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
52 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
53 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
54 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
57 static const uint16_t _roadveh_full_adder[] = {
58 0, 88, 0, 0, 0, 0, 48, 48,
59 48, 48, 0, 0, 64, 64, 0, 16,
60 16, 0, 88, 0, 0, 0, 0, 48,
61 48, 48, 48, 0, 0, 64, 64, 0,
62 16, 16, 0, 88, 0, 0, 0, 0,
63 48, 48, 48, 48, 0, 0, 64, 64,
64 0, 16, 16, 0, 8, 8, 8, 8,
65 0, 0, 0, 8, 8, 8, 8
67 static_assert(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
69 template <>
70 bool IsValidImageIndex<VEH_ROAD>(uint8_t image_index)
72 return image_index < lengthof(_roadveh_images);
75 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
76 TRACKDIR_RVREV_NE, TRACKDIR_RVREV_SE, TRACKDIR_RVREV_SW, TRACKDIR_RVREV_NW
79 /**
80 * Check whether a roadvehicle is a bus
81 * @return true if bus
83 bool RoadVehicle::IsBus() const
85 assert(this->IsFrontEngine());
86 return IsCargoInClass(this->cargo_type, CC_PASSENGERS);
89 /**
90 * Get the width of a road vehicle image in the GUI.
91 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
92 * @return Width in pixels
94 int RoadVehicle::GetDisplayImageWidth(Point *offset) const
96 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
98 if (offset != nullptr) {
99 offset->x = ScaleSpriteTrad(reference_width) / 2;
100 offset->y = 0;
102 return ScaleSpriteTrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
105 static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
107 const Engine *e = Engine::Get(engine);
108 uint8_t spritenum = e->u.road.image_index;
110 if (is_custom_sprite(spritenum)) {
111 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
112 if (result->IsValid()) return;
114 spritenum = e->original_image_index;
117 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
118 result->Set(DIR_W + _roadveh_images[spritenum]);
121 void RoadVehicle::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
123 uint8_t spritenum = this->spritenum;
125 if (is_custom_sprite(spritenum)) {
126 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
127 if (result->IsValid()) return;
129 spritenum = this->GetEngine()->original_image_index;
132 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
133 SpriteID sprite = direction + _roadveh_images[spritenum];
135 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
137 result->Set(sprite);
141 * Draw a road vehicle engine.
142 * @param left Left edge to draw within.
143 * @param right Right edge to draw within.
144 * @param preferred_x Preferred position of the engine.
145 * @param y Vertical position of the engine.
146 * @param engine Engine to draw
147 * @param pal Palette to use.
149 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
151 VehicleSpriteSeq seq;
152 GetRoadVehIcon(engine, image_type, &seq);
154 Rect rect;
155 seq.GetBounds(&rect);
156 preferred_x = Clamp(preferred_x,
157 left - UnScaleGUI(rect.left),
158 right - UnScaleGUI(rect.right));
160 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
164 * Get the size of the sprite of a road vehicle sprite heading west (used for lists).
165 * @param engine The engine to get the sprite from.
166 * @param[out] width The width of the sprite.
167 * @param[out] height The height of the sprite.
168 * @param[out] xoffs Number of pixels to shift the sprite to the right.
169 * @param[out] yoffs Number of pixels to shift the sprite downwards.
170 * @param image_type Context the sprite is used in.
172 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
174 VehicleSpriteSeq seq;
175 GetRoadVehIcon(engine, image_type, &seq);
177 Rect rect;
178 seq.GetBounds(&rect);
180 width = UnScaleGUI(rect.Width());
181 height = UnScaleGUI(rect.Height());
182 xoffs = UnScaleGUI(rect.left);
183 yoffs = UnScaleGUI(rect.top);
187 * Get length of a road vehicle.
188 * @param v Road vehicle to query length.
189 * @return Length of the given road vehicle.
191 static uint GetRoadVehLength(const RoadVehicle *v)
193 const Engine *e = v->GetEngine();
194 uint length = VEHICLE_LENGTH;
196 uint16_t veh_len = CALLBACK_FAILED;
197 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
198 /* Use callback 36 */
199 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
200 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
201 } else {
202 /* Use callback 11 */
203 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
205 if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
206 if (veh_len != 0) {
207 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
210 return length;
214 * Update the cache of a road vehicle.
215 * @param v Road vehicle needing an update of its cache.
216 * @param same_length should length of vehicles stay the same?
217 * @pre \a v must be first road vehicle.
219 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
221 assert(v->type == VEH_ROAD);
222 assert(v->IsFrontEngine());
224 v->InvalidateNewGRFCacheOfChain();
226 v->gcache.cached_total_length = 0;
228 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
229 /* Check the v->first cache. */
230 assert(u->First() == v);
232 /* Update the 'first engine' */
233 u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
235 /* Update the length of the vehicle. */
236 uint veh_len = GetRoadVehLength(u);
237 /* Verify length hasn't changed. */
238 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
240 u->gcache.cached_veh_length = veh_len;
241 v->gcache.cached_total_length += u->gcache.cached_veh_length;
243 /* Update visual effect */
244 u->UpdateVisualEffect();
246 /* Update cargo aging period. */
247 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
250 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
251 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
255 * Build a road vehicle.
256 * @param flags type of operation.
257 * @param tile tile of the depot where road vehicle is built.
258 * @param e the engine to build.
259 * @param[out] ret the vehicle that has been built.
260 * @return the cost of this operation or an error.
262 CommandCost CmdBuildRoadVehicle(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
264 /* Check that the vehicle can drive on the road in question */
265 RoadType rt = e->u.road.roadtype;
266 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
267 if (!HasTileAnyRoadType(tile, rti->powered_roadtypes)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
269 if (flags & DC_EXEC) {
270 const RoadVehicleInfo *rvi = &e->u.road;
272 RoadVehicle *v = new RoadVehicle();
273 *ret = v;
274 v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
275 v->owner = _current_company;
277 v->tile = tile;
278 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
279 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
280 v->x_pos = x;
281 v->y_pos = y;
282 v->z_pos = GetSlopePixelZ(x, y, true);
284 v->state = RVSB_IN_DEPOT;
285 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
287 v->spritenum = rvi->image_index;
288 v->cargo_type = e->GetDefaultCargoType();
289 assert(IsValidCargoID(v->cargo_type));
290 v->cargo_cap = rvi->capacity;
291 v->refit_cap = 0;
293 v->last_station_visited = INVALID_STATION;
294 v->last_loading_station = INVALID_STATION;
295 v->engine_type = e->index;
296 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
298 v->reliability = e->reliability;
299 v->reliability_spd_dec = e->reliability_spd_dec;
300 v->max_age = e->GetLifeLengthInDays();
302 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
304 v->date_of_last_service = TimerGameEconomy::date;
305 v->date_of_last_service_newgrf = TimerGameCalendar::date;
306 v->build_year = TimerGameCalendar::year;
308 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
309 v->random_bits = Random();
310 v->SetFrontEngine();
312 v->roadtype = rt;
313 v->compatible_roadtypes = rti->powered_roadtypes;
314 v->gcache.cached_veh_length = VEHICLE_LENGTH;
316 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
317 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
319 AddArticulatedParts(v);
320 v->InvalidateNewGRFCacheOfChain();
322 /* Call various callbacks after the whole consist has been constructed */
323 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
324 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
325 u->refit_cap = 0;
326 v->InvalidateNewGRFCache();
327 u->InvalidateNewGRFCache();
329 RoadVehUpdateCache(v);
330 /* Initialize cached values for realistic acceleration. */
331 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) v->CargoChanged();
333 v->UpdatePosition();
335 CheckConsistencyOfArticulatedVehicle(v);
338 return CommandCost();
341 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
343 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
345 switch (_settings_game.pf.pathfinder_for_roadvehs) {
346 case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
347 case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
349 default: NOT_REACHED();
353 ClosestDepot RoadVehicle::FindClosestDepot()
355 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
356 if (rfdd.best_length == UINT_MAX) return ClosestDepot();
358 return ClosestDepot(rfdd.tile, GetDepotIndex(rfdd.tile));
362 * Turn a roadvehicle around.
363 * @param flags operation to perform
364 * @param veh_id vehicle ID to turn
365 * @return the cost of this operation or an error
367 CommandCost CmdTurnRoadVeh(DoCommandFlag flags, VehicleID veh_id)
369 RoadVehicle *v = RoadVehicle::GetIfValid(veh_id);
370 if (v == nullptr) return CMD_ERROR;
372 if (!v->IsPrimaryVehicle()) return CMD_ERROR;
374 CommandCost ret = CheckOwnership(v->owner);
375 if (ret.Failed()) return ret;
377 if ((v->vehstatus & VS_STOPPED) ||
378 (v->vehstatus & VS_CRASHED) ||
379 v->breakdown_ctr != 0 ||
380 v->overtaking != 0 ||
381 v->state == RVSB_WORMHOLE ||
382 v->IsInDepot() ||
383 v->current_order.IsType(OT_LOADING)) {
384 return CMD_ERROR;
387 if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CMD_ERROR;
389 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && DirToDiagDir(v->direction) == GetTunnelBridgeDirection(v->tile)) return CMD_ERROR;
391 if (flags & DC_EXEC) {
392 v->reverse_ctr = 180;
394 /* Unbunching data is no longer valid. */
395 v->ResetDepotUnbunching();
398 return CommandCost();
402 void RoadVehicle::MarkDirty()
404 for (RoadVehicle *v = this; v != nullptr; v = v->Next()) {
405 v->colourmap = PAL_NONE;
406 v->UpdateViewport(true, false);
408 this->CargoChanged();
411 void RoadVehicle::UpdateDeltaXY()
413 static const int8_t _delta_xy_table[8][10] = {
414 /* 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 */
415 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
416 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
417 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
418 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
419 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
420 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
421 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
422 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
425 int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
426 if (!IsDiagonalDirection(this->direction)) shorten >>= 1;
428 const int8_t *bb = _delta_xy_table[this->direction];
429 this->x_bb_offs = bb[5] + bb[9] * shorten;
430 this->y_bb_offs = bb[4] + bb[8] * shorten;;
431 this->x_offs = bb[3];
432 this->y_offs = bb[2];
433 this->x_extent = bb[1] + bb[7] * shorten;
434 this->y_extent = bb[0] + bb[6] * shorten;
435 this->z_extent = 6;
439 * Calculates the maximum speed of the vehicle under its current conditions.
440 * @return Maximum speed of the vehicle.
442 inline int RoadVehicle::GetCurrentMaxSpeed() const
444 int max_speed = this->gcache.cached_max_track_speed;
446 /* Limit speed to 50% while reversing, 75% in curves. */
447 for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) {
448 if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
449 if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) {
450 max_speed = this->gcache.cached_max_track_speed / 2;
451 break;
452 } else if ((u->direction & 1) == 0) {
453 max_speed = this->gcache.cached_max_track_speed * 3 / 4;
457 /* Vehicle is on the middle part of a bridge. */
458 if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
459 max_speed = std::min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
463 return std::min(max_speed, this->current_order.GetMaxSpeed() * 2);
467 * Delete last vehicle of a chain road vehicles.
468 * @param v First roadvehicle.
470 static void DeleteLastRoadVeh(RoadVehicle *v)
472 RoadVehicle *first = v->First();
473 Vehicle *u = v;
474 for (; v->Next() != nullptr; v = v->Next()) u = v;
475 u->SetNext(nullptr);
476 v->last_station_visited = first->last_station_visited; // for PreDestructor
478 /* Only leave the road stop when we're really gone. */
479 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
481 delete v;
484 static void RoadVehSetRandomDirection(RoadVehicle *v)
486 static const DirDiff delta[] = {
487 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
490 do {
491 uint32_t r = Random();
493 v->direction = ChangeDir(v->direction, delta[r & 3]);
494 v->UpdateViewport(true, true);
495 } while ((v = v->Next()) != nullptr);
499 * Road vehicle chain has crashed.
500 * @param v First roadvehicle.
501 * @return whether the chain still exists.
503 static bool RoadVehIsCrashed(RoadVehicle *v)
505 v->crashed_ctr++;
506 if (v->crashed_ctr == 2) {
507 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
508 } else if (v->crashed_ctr <= 45) {
509 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
510 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
511 bool ret = v->Next() != nullptr;
512 DeleteLastRoadVeh(v);
513 return ret;
516 return true;
520 * Check routine whether a road and a train vehicle have collided.
521 * @param v %Train vehicle to test.
522 * @param data Road vehicle to test.
523 * @return %Train vehicle if the vehicles collided, else \c nullptr.
525 static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
527 const Vehicle *u = (Vehicle*)data;
529 return (v->type == VEH_TRAIN &&
530 abs(v->z_pos - u->z_pos) <= 6 &&
531 abs(v->x_pos - u->x_pos) <= 4 &&
532 abs(v->y_pos - u->y_pos) <= 4) ? v : nullptr;
535 uint RoadVehicle::Crash(bool flooded)
537 uint pass = this->GroundVehicleBase::Crash(flooded);
538 if (this->IsFrontEngine()) {
539 pass += 1; // driver
541 /* If we're in a drive through road stop we ought to leave it */
542 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
543 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
546 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
547 return pass;
550 static void RoadVehCrash(RoadVehicle *v)
552 uint pass = v->Crash();
554 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
555 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
557 SetDParam(0, pass);
558 StringID newsitem = (pass == 1) ? STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH;
559 NewsType newstype = NT_ACCIDENT;
561 if (v->owner != _local_company) {
562 newstype = NT_ACCIDENT_OTHER;
565 AddTileNewsItem(newsitem, newstype, v->tile);
567 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
568 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
571 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
573 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
574 if (u->state == RVSB_WORMHOLE) continue;
576 TileIndex tile = u->tile;
578 if (!IsLevelCrossingTile(tile)) continue;
580 if (HasVehicleOnPosXY(v->x_pos, v->y_pos, u, EnumCheckRoadVehCrashTrain)) {
581 RoadVehCrash(v);
582 return true;
586 return false;
589 TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
591 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
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;
600 return st->xy;
603 static void StartRoadVehSound(const RoadVehicle *v)
605 if (!PlayVehicleSound(v, VSE_START)) {
606 SoundID s = RoadVehInfo(v->engine_type)->sfx;
607 if (s == SND_19_DEPARTURE_OLD_RV_1 && (v->tick_counter & 3) == 0) {
608 s = SND_1A_DEPARTURE_OLD_RV_2;
610 SndPlayVehicleFx(s, v);
614 struct RoadVehFindData {
615 int x;
616 int y;
617 const Vehicle *veh;
618 Vehicle *best;
619 uint best_diff;
620 Direction dir;
623 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
625 static const int8_t dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
626 static const int8_t dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
628 RoadVehFindData *rvf = (RoadVehFindData*)data;
630 short x_diff = v->x_pos - rvf->x;
631 short y_diff = v->y_pos - rvf->y;
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);
644 if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
645 rvf->best = v;
646 rvf->best_diff = diff;
650 return nullptr;
653 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
655 RoadVehFindData rvf;
656 RoadVehicle *front = v->First();
658 if (front->reverse_ctr != 0) return nullptr;
660 rvf.x = x;
661 rvf.y = y;
662 rvf.dir = dir;
663 rvf.veh = v;
664 rvf.best_diff = UINT_MAX;
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);
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 nullptr;
682 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return nullptr;
684 return RoadVehicle::From(rvf.best);
688 * A road vehicle arrives at a station. If it is the first time, create a news item.
689 * @param v Road vehicle that arrived.
690 * @param st Station where the road vehicle arrived.
692 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
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 RoadTypeIsRoad(v->roadtype) ? 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
705 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
706 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
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 RoadTypeIsRoad(v->roadtype) ? 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
719 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
720 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
726 * This function looks at the vehicle and updates its speed (cur_speed
727 * and subspeed) variables. Furthermore, it returns the distance that
728 * the vehicle can drive this tick. #Vehicle::GetAdvanceDistance() determines
729 * the distance to drive before moving a step on the map.
730 * @return distance to drive.
732 int RoadVehicle::UpdateSpeed()
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());
739 case AM_REALISTIC:
740 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
744 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
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
752 x = x - v->x_pos + 1;
753 y = y - v->y_pos + 1;
755 if ((uint)x > 2 || (uint)y > 2) return v->direction;
756 return _roadveh_new_dir[y * 4 + x];
759 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
761 Direction new_dir = RoadVehGetNewDirection(v, x, y);
762 Direction old_dir = v->direction;
763 DirDiff delta;
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);
770 struct OvertakeData {
771 const RoadVehicle *u;
772 const RoadVehicle *v;
773 TileIndex tile;
774 Trackdir trackdir;
777 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
779 const OvertakeData *od = (OvertakeData*)data;
781 return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : nullptr;
785 * Check if overtaking is possible on a piece of track
787 * @param od Information about the tile and the involved vehicles
788 * @return true if we have to abort overtaking
790 static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
792 if (!HasTileAnyRoadType(od->tile, od->v->compatible_roadtypes)) return true;
793 TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, GetRoadTramType(od->v->roadtype));
794 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
795 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
796 TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
798 /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
799 if (!HasBit(trackdirbits, od->trackdir) || (trackbits & ~TRACK_BIT_CROSS) || (red_signals != TRACKDIR_BIT_NONE)) return true;
801 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
802 return HasVehicleOnPos(od->tile, od, EnumFindVehBlockingOvertake);
805 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
807 OvertakeData od;
809 od.v = v;
810 od.u = u;
812 /* Trams can't overtake other trams */
813 if (RoadTypeIsTram(v->roadtype)) return;
815 /* Don't overtake in stations */
816 if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
818 /* For now, articulated road vehicles can't overtake anything. */
819 if (v->HasArticulatedPart()) return;
821 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
822 if (v->direction != u->direction || !(v->direction & 1)) return;
824 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
825 if (v->state >= RVSB_IN_ROAD_STOP || !IsStraightRoadTrackdir((Trackdir)(v->state & RVSB_TRACKDIR_MASK))) return;
827 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
828 * accelerating, take the maximum speed for the comparison, else the current speed.
829 * Original acceleration always accelerates, so always use the maximum speed. */
830 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
831 if (u_speed >= v->GetCurrentMaxSpeed() &&
832 !(u->vehstatus & VS_STOPPED) &&
833 u->cur_speed != 0) {
834 return;
837 od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
839 /* Are the current and the next tile suitable for overtaking?
840 * - Does the track continue along od.trackdir
841 * - No junctions
842 * - No barred levelcrossing
843 * - No other vehicles in the way
845 od.tile = v->tile;
846 if (CheckRoadBlockedForOvertaking(&od)) return;
848 od.tile = v->tile + TileOffsByDiagDir(DirToDiagDir(v->direction));
849 if (CheckRoadBlockedForOvertaking(&od)) return;
851 /* When the vehicle in front of us is stopped we may only take
852 * half the time to pass it than when the vehicle is moving. */
853 v->overtaking_ctr = (od.u->cur_speed == 0 || (od.u->vehstatus & VS_STOPPED)) ? RV_OVERTAKE_TIMEOUT / 2 : 0;
854 v->overtaking = RVSB_DRIVE_SIDE;
857 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
859 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
861 if (old_z < v->z_pos) {
862 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
863 } else {
864 uint16_t spd = v->cur_speed + 2;
865 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
869 static int PickRandomBit(uint bits)
871 uint i;
872 uint num = RandomRange(CountBits(bits));
874 for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
875 return i;
879 * Returns direction to for a road vehicle to take or
880 * INVALID_TRACKDIR if the direction is currently blocked
881 * @param v the Vehicle to do the pathfinding for
882 * @param tile the where to start the pathfinding
883 * @param enterdir the direction the vehicle enters the tile from
884 * @return the Trackdir to take
886 static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
888 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
890 TileIndex desttile;
891 Trackdir best_track;
892 bool path_found = true;
894 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, GetRoadTramType(v->roadtype));
895 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
896 TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
898 if (IsTileType(tile, MP_ROAD)) {
899 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir)) {
900 /* Road depot owned by another company or with the wrong orientation */
901 trackdirs = TRACKDIR_BIT_NONE;
903 } else if (IsTileType(tile, MP_STATION) && IsBayRoadStopTile(tile)) {
904 /* Standard road stop (drive-through stops are treated as normal road) */
906 if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
907 /* different station owner or wrong orientation or the vehicle has articulated parts */
908 trackdirs = TRACKDIR_BIT_NONE;
909 } else {
910 /* Our station */
911 RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
913 if (GetRoadStopType(tile) != rstype) {
914 /* Wrong station type */
915 trackdirs = TRACKDIR_BIT_NONE;
916 } else {
917 /* Proper station type, check if there is free loading bay */
918 if (!_settings_game.pf.roadveh_queue && IsBayRoadStopTile(tile) &&
919 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
920 /* Station is full and RV queuing is off */
921 trackdirs = TRACKDIR_BIT_NONE;
926 /* The above lookups should be moved to GetTileTrackStatus in the
927 * future, but that requires more changes to the pathfinder and other
928 * stuff, probably even more arguments to GTTS.
931 /* Remove tracks unreachable from the enter dir */
932 trackdirs &= DiagdirReachesTrackdirs(enterdir);
933 if (trackdirs == TRACKDIR_BIT_NONE) {
934 /* If vehicle expected a path, it no longer exists, so invalidate it. */
935 if (!v->path.empty()) v->path.clear();
936 /* No reachable tracks, so we'll reverse */
937 return_track(_road_reverse_table[enterdir]);
940 if (v->reverse_ctr != 0) {
941 bool reverse = true;
942 if (RoadTypeIsTram(v->roadtype)) {
943 /* Trams may only reverse on a tile if it contains at least the straight
944 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
945 RoadBits rb = GetAnyRoadBits(tile, RTT_TRAM);
946 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
947 reverse = ((rb & straight) == straight) ||
948 (rb == DiagDirToRoadBits(enterdir));
950 if (reverse) {
951 v->reverse_ctr = 0;
952 if (v->tile != tile) {
953 return_track(_road_reverse_table[enterdir]);
958 desttile = v->dest_tile;
959 if (desttile == 0) {
960 /* We've got no destination, pick a random track */
961 return_track(PickRandomBit(trackdirs));
964 /* Only one track to choose between? */
965 if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
966 if (!v->path.empty() && v->path.tile.front() == tile) {
967 /* Vehicle expected a choice here, invalidate its path. */
968 v->path.clear();
970 return_track(FindFirstBit(trackdirs));
973 /* Attempt to follow cached path. */
974 if (!v->path.empty()) {
975 if (v->path.tile.front() != tile) {
976 /* Vehicle didn't expect a choice here, invalidate its path. */
977 v->path.clear();
978 } else {
979 Trackdir trackdir = v->path.td.front();
981 if (HasBit(trackdirs, trackdir)) {
982 v->path.td.pop_front();
983 v->path.tile.pop_front();
984 return_track(trackdir);
987 /* Vehicle expected a choice which is no longer available. */
988 v->path.clear();
992 switch (_settings_game.pf.pathfinder_for_roadvehs) {
993 case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, path_found); break;
994 case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found, v->path); break;
996 default: NOT_REACHED();
998 v->HandlePathfindingResult(path_found);
1000 found_best_track:;
1002 if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
1004 return best_track;
1007 struct RoadDriveEntry {
1008 byte x, y;
1011 #include "table/roadveh_movement.h"
1013 bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
1015 /* Don't leave unless v and following wagons are in the depot. */
1016 for (const RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1017 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
1020 DiagDirection dir = GetRoadDepotDirection(v->tile);
1021 v->direction = DiagDirToDir(dir);
1023 Trackdir tdir = DiagDirToDiagTrackdir(dir);
1024 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
1026 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1027 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1029 if (first) {
1030 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1031 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1032 VehicleEnterDepot(v);
1033 return true;
1036 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != nullptr) return true;
1038 VehicleServiceInDepot(v);
1039 v->LeaveUnbunchingDepot();
1041 StartRoadVehSound(v);
1043 /* Vehicle is about to leave a depot */
1044 v->cur_speed = 0;
1047 v->vehstatus &= ~VS_HIDDEN;
1048 v->state = tdir;
1049 v->frame = RVC_DEPOT_START_FRAME;
1051 v->x_pos = x;
1052 v->y_pos = y;
1053 v->UpdatePosition();
1054 v->UpdateInclination(true, true);
1056 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1058 return true;
1061 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1063 if (prev->tile == v->tile && !already_reversed) {
1064 /* If the previous vehicle is on the same tile as this vehicle is
1065 * then it must have reversed. */
1066 return _road_reverse_table[entry_dir];
1069 byte prev_state = prev->state;
1070 Trackdir dir;
1072 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1073 DiagDirection diag_dir = INVALID_DIAGDIR;
1075 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1076 diag_dir = GetTunnelBridgeDirection(tile);
1077 } else if (IsRoadDepotTile(tile)) {
1078 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1081 if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1082 dir = DiagDirToDiagTrackdir(diag_dir);
1083 } else {
1084 if (already_reversed && prev->tile != tile) {
1086 * The vehicle has reversed, but did not go straight back.
1087 * It immediately turn onto another tile. This means that
1088 * the roadstate of the previous vehicle cannot be used
1089 * as the direction we have to go with this vehicle.
1091 * Next table is build in the following way:
1092 * - first row for when the vehicle in front went to the northern or
1093 * western tile, second for southern and eastern.
1094 * - columns represent the entry direction.
1095 * - cell values are determined by the Trackdir one has to take from
1096 * the entry dir (column) to the tile in north or south by only
1097 * going over the trackdirs used for turning 90 degrees, i.e.
1098 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1100 static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1101 { TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N, TRACKDIR_UPPER_E },
1102 { TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }};
1103 dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1104 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1105 dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1106 } else if (prev_state < TRACKDIR_END) {
1107 dir = (Trackdir)prev_state;
1108 } else {
1109 return INVALID_TRACKDIR;
1113 /* Do some sanity checking. */
1114 static const RoadBits required_roadbits[] = {
1115 ROAD_X, ROAD_Y, ROAD_NW | ROAD_NE, ROAD_SW | ROAD_SE,
1116 ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1118 RoadBits required = required_roadbits[dir & 0x07];
1120 if ((required & GetAnyRoadBits(tile, GetRoadTramType(v->roadtype), true)) == ROAD_NONE) {
1121 dir = INVALID_TRACKDIR;
1124 return dir;
1128 * Can a tram track build without destruction on the given tile?
1129 * @param c the company that would be building the tram tracks
1130 * @param t the tile to build on.
1131 * @param rt the tram type to build.
1132 * @param r the road bits needed.
1133 * @return true when a track track can be build on 't'
1135 static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadType rt, RoadBits r)
1137 /* The 'current' company is not necessarily the owner of the vehicle. */
1138 Backup<CompanyID> cur_company(_current_company, c, FILE_LINE);
1140 CommandCost ret = Command<CMD_BUILD_ROAD>::Do(DC_NO_WATER, t, r, rt, DRD_NONE, 0);
1142 cur_company.Restore();
1143 return ret.Succeeded();
1146 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1148 if (v->overtaking != 0) {
1149 if (IsTileType(v->tile, MP_STATION)) {
1150 /* Force us to be not overtaking! */
1151 v->overtaking = 0;
1152 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1153 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1154 * if the vehicle started a corner. To protect that, only allow an abort of
1155 * overtake if we are on straight roads */
1156 if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->state)) {
1157 v->overtaking = 0;
1162 /* If this vehicle is in a depot and we've reached this point it must be
1163 * one of the articulated parts. It will stay in the depot until activated
1164 * by the previous vehicle in the chain when it gets to the right place. */
1165 if (v->IsInDepot()) return true;
1167 if (v->state == RVSB_WORMHOLE) {
1168 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1169 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
1171 if (v->IsFrontEngine()) {
1172 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1173 if (u != nullptr) {
1174 v->cur_speed = u->First()->cur_speed;
1175 return false;
1179 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
1180 /* Vehicle has just entered a bridge or tunnel */
1181 v->x_pos = gp.x;
1182 v->y_pos = gp.y;
1183 v->UpdatePosition();
1184 v->UpdateInclination(true, true);
1185 return true;
1188 v->x_pos = gp.x;
1189 v->y_pos = gp.y;
1190 v->UpdatePosition();
1191 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
1192 return true;
1195 /* Get move position data for next frame.
1196 * For a drive-through road stop use 'straight road' move data.
1197 * In this case v->state is masked to give the road stop entry direction. */
1198 RoadDriveEntry rd = _road_drive_data[GetRoadTramType(v->roadtype)][(
1199 (HasBit(v->state, RVS_IN_DT_ROAD_STOP) ? v->state & RVSB_ROAD_STOP_TRACKDIR_MASK : v->state) +
1200 (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1202 if (rd.x & RDE_NEXT_TILE) {
1203 TileIndex tile = v->tile + TileOffsByDiagDir((DiagDirection)(rd.x & 3));
1204 Trackdir dir;
1206 if (v->IsFrontEngine()) {
1207 /* If this is the front engine, look for the right path. */
1208 if (HasTileAnyRoadType(tile, v->compatible_roadtypes)) {
1209 dir = RoadFindPathToDest(v, tile, (DiagDirection)(rd.x & 3));
1210 } else {
1211 dir = _road_reverse_table[(DiagDirection)(rd.x & 3)];
1213 } else {
1214 dir = FollowPreviousRoadVehicle(v, prev, tile, (DiagDirection)(rd.x & 3), false);
1217 if (dir == INVALID_TRACKDIR) {
1218 if (!v->IsFrontEngine()) FatalError("Disconnecting road vehicle.");
1219 v->cur_speed = 0;
1220 return false;
1223 again:
1224 uint start_frame = RVC_DEFAULT_START_FRAME;
1225 if (IsReversingRoadTrackdir(dir)) {
1226 /* When turning around we can't be overtaking. */
1227 v->overtaking = 0;
1229 /* Turning around */
1230 if (RoadTypeIsTram(v->roadtype)) {
1231 /* Determine the road bits the tram needs to be able to turn around
1232 * using the 'big' corner loop. */
1233 RoadBits needed;
1234 switch (dir) {
1235 default: NOT_REACHED();
1236 case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1237 case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1238 case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1239 case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1241 if ((v->Previous() != nullptr && v->Previous()->tile == tile) ||
1242 (v->IsFrontEngine() && IsNormalRoadTile(tile) && !HasRoadWorks(tile) &&
1243 HasTileAnyRoadType(tile, v->compatible_roadtypes) &&
1244 (needed & GetRoadBits(tile, RTT_TRAM)) != ROAD_NONE)) {
1246 * Taking the 'big' corner for trams only happens when:
1247 * - The previous vehicle in this (articulated) tram chain is
1248 * already on the 'next' tile, we just follow them regardless of
1249 * anything. When it is NOT on the 'next' tile, the tram started
1250 * doing a reversing turn when the piece of tram track on the next
1251 * tile did not exist yet. Do not use the big tram loop as that is
1252 * going to cause the tram to split up.
1253 * - Or the front of the tram can drive over the next tile.
1255 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, v->roadtype, needed) || ((~needed & GetAnyRoadBits(v->tile, RTT_TRAM, false)) == ROAD_NONE)) {
1257 * Taking the 'small' corner for trams only happens when:
1258 * - We are not the from vehicle of an articulated tram.
1259 * - Or when the company cannot build on the next tile.
1261 * The 'small' corner means that the vehicle is on the end of a
1262 * tram track and needs to start turning there. To do this properly
1263 * the tram needs to start at an offset in the tram turning 'code'
1264 * for 'big' corners. It furthermore does not go to the next tile,
1265 * so that needs to be fixed too.
1267 tile = v->tile;
1268 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1269 } else {
1270 /* The company can build on the next tile, so wait till they do. */
1271 v->cur_speed = 0;
1272 return false;
1274 } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1275 v->cur_speed = 0;
1276 return false;
1277 } else {
1278 tile = v->tile;
1282 /* Get position data for first frame on the new tile */
1283 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1285 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1286 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1288 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1289 if (v->IsFrontEngine()) {
1290 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1291 if (u != nullptr) {
1292 v->cur_speed = u->First()->cur_speed;
1293 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1294 v->path.tile.push_front(tile);
1295 v->path.td.push_front(dir);
1296 return false;
1300 uint32_t r = VehicleEnterTile(v, tile, x, y);
1301 if (HasBit(r, VETS_CANNOT_ENTER)) {
1302 if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1303 v->cur_speed = 0;
1304 return false;
1306 /* Try an about turn to re-enter the previous tile */
1307 dir = _road_reverse_table[rd.x & 3];
1308 goto again;
1311 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1312 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1313 /* New direction is trying to turn vehicle around.
1314 * We can't turn at the exit of a road stop so wait.*/
1315 v->cur_speed = 0;
1316 return false;
1319 /* If we are a drive through road stop and the next tile is of
1320 * the same road stop and the next tile isn't this one (i.e. we
1321 * are not reversing), then keep the reservation and state.
1322 * This way we will not be shortly unregister from the road
1323 * stop. It also makes it possible to load when on the edge of
1324 * two road stops; otherwise you could get vehicles that should
1325 * be loading but are not actually loading. */
1326 if (IsDriveThroughStopTile(v->tile) &&
1327 RoadStop::IsDriveThroughRoadStopContinuation(v->tile, tile) &&
1328 v->tile != tile) {
1329 /* So, keep 'our' state */
1330 dir = (Trackdir)v->state;
1331 } else if (IsRoadStop(v->tile)) {
1332 /* We're not continuing our drive through road stop, so leave. */
1333 RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
1337 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1338 TileIndex old_tile = v->tile;
1340 v->tile = tile;
1341 v->state = (byte)dir;
1342 v->frame = start_frame;
1343 RoadTramType rtt = GetRoadTramType(v->roadtype);
1344 if (GetRoadType(old_tile, rtt) != GetRoadType(tile, rtt)) {
1345 if (v->IsFrontEngine()) {
1346 RoadVehUpdateCache(v);
1348 v->First()->CargoChanged();
1351 if (new_dir != v->direction) {
1352 v->direction = new_dir;
1353 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1355 v->x_pos = x;
1356 v->y_pos = y;
1357 v->UpdatePosition();
1358 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1359 return true;
1362 if (rd.x & RDE_TURNED) {
1363 /* Vehicle has finished turning around, it will now head back onto the same tile */
1364 Trackdir dir;
1365 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1367 if (RoadTypeIsTram(v->roadtype) && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, RTT_TRAM, true))) {
1369 * The tram is turning around with one tram 'roadbit'. This means that
1370 * it is using the 'big' corner 'drive data'. However, to support the
1371 * trams to take a small corner, there is a 'turned' marker in the middle
1372 * of the turning 'drive data'. When the tram took the long corner, we
1373 * will still use the 'big' corner drive data, but we advance it one
1374 * frame. We furthermore set the driving direction so the turning is
1375 * going to be properly shown.
1377 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1378 switch (rd.x & 0x3) {
1379 default: NOT_REACHED();
1380 case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1381 case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1382 case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1383 case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1385 } else {
1386 if (v->IsFrontEngine()) {
1387 /* If this is the front engine, look for the right path. */
1388 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1389 } else {
1390 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1394 if (dir == INVALID_TRACKDIR) {
1395 v->cur_speed = 0;
1396 return false;
1399 const RoadDriveEntry *rdp = _road_drive_data[GetRoadTramType(v->roadtype)][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1401 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1402 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1404 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1405 if (v->IsFrontEngine()) {
1406 const Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1407 if (u != nullptr) {
1408 v->cur_speed = u->First()->cur_speed;
1409 /* We might be blocked, prevent pathfinding rerun as we already know where we are heading to. */
1410 v->path.tile.push_front(v->tile);
1411 v->path.td.push_front(dir);
1412 return false;
1416 uint32_t r = VehicleEnterTile(v, v->tile, x, y);
1417 if (HasBit(r, VETS_CANNOT_ENTER)) {
1418 v->cur_speed = 0;
1419 return false;
1422 v->state = dir;
1423 v->frame = turn_around_start_frame;
1425 if (new_dir != v->direction) {
1426 v->direction = new_dir;
1427 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1430 v->x_pos = x;
1431 v->y_pos = y;
1432 v->UpdatePosition();
1433 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1434 return true;
1437 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1438 * it's on a depot tile, check if it's time to activate the next vehicle in
1439 * the chain yet. */
1440 if (v->Next() != nullptr && IsRoadDepotTile(v->tile)) {
1441 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1442 RoadVehLeaveDepot(v->Next(), false);
1446 /* Calculate new position for the vehicle */
1447 int x = (v->x_pos & ~15) + (rd.x & 15);
1448 int y = (v->y_pos & ~15) + (rd.y & 15);
1450 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1452 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1453 /* Vehicle is not in a road stop.
1454 * Check for another vehicle to overtake */
1455 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1457 if (u != nullptr) {
1458 u = u->First();
1459 /* There is a vehicle in front overtake it if possible */
1460 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1461 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1463 /* In case an RV is stopped in a road stop, why not try to load? */
1464 if (v->cur_speed == 0 && IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1465 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1466 v->owner == GetTileOwner(v->tile) && !v->current_order.IsType(OT_LEAVESTATION) &&
1467 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK)) {
1468 Station *st = Station::GetByTile(v->tile);
1469 v->last_station_visited = st->index;
1470 RoadVehArrivesAt(v, st);
1471 v->BeginLoading();
1473 return false;
1477 Direction old_dir = v->direction;
1478 if (new_dir != old_dir) {
1479 v->direction = new_dir;
1480 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1482 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1483 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1484 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1485 * The short (inner) curve has 8 frames, this elongates it to 10. */
1486 v->UpdateViewport(true, true);
1487 return true;
1490 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1491 * if the vehicle is in a drive-through road stop and this is the destination station
1492 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1493 * (the station test and stop type test ensure that other vehicles, using the road stop as
1494 * a through route, do not stop) */
1495 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1496 _road_stop_stop_frame[v->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)] == v->frame) ||
1497 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1498 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1499 v->owner == GetTileOwner(v->tile) &&
1500 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
1501 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1503 RoadStop *rs = RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile));
1504 Station *st = Station::GetByTile(v->tile);
1506 /* Vehicle is at the stop position (at a bay) in a road stop.
1507 * Note, if vehicle is loading/unloading it has already been handled,
1508 * so if we get here the vehicle has just arrived or is just ready to leave. */
1509 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1510 /* Vehicle has arrived at a bay in a road stop */
1512 if (IsDriveThroughStopTile(v->tile)) {
1513 TileIndex next_tile = TileAddByDir(v->tile, v->direction);
1515 /* Check if next inline bay is free and has compatible road. */
1516 if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && HasTileAnyRoadType(next_tile, v->compatible_roadtypes)) {
1517 v->frame++;
1518 v->x_pos = x;
1519 v->y_pos = y;
1520 v->UpdatePosition();
1521 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1522 return true;
1526 rs->SetEntranceBusy(false);
1527 SetBit(v->state, RVS_ENTERED_STOP);
1529 v->last_station_visited = st->index;
1531 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1532 RoadVehArrivesAt(v, st);
1533 v->BeginLoading();
1534 return false;
1536 } else {
1537 /* Vehicle is ready to leave a bay in a road stop */
1538 if (rs->IsEntranceBusy()) {
1539 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1540 v->cur_speed = 0;
1541 return false;
1543 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1546 if (IsBayRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1548 StartRoadVehSound(v);
1549 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1552 /* Check tile position conditions - i.e. stop position in depot,
1553 * entry onto bridge or into tunnel */
1554 uint32_t r = VehicleEnterTile(v, v->tile, x, y);
1555 if (HasBit(r, VETS_CANNOT_ENTER)) {
1556 v->cur_speed = 0;
1557 return false;
1560 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1561 v->current_order.Free();
1564 /* Move to next frame unless vehicle arrived at a stop position
1565 * in a depot or entered a tunnel/bridge */
1566 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1567 v->x_pos = x;
1568 v->y_pos = y;
1569 v->UpdatePosition();
1570 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true));
1571 return true;
1574 static bool RoadVehController(RoadVehicle *v)
1576 /* decrease counters */
1577 v->current_order_time++;
1578 if (v->reverse_ctr != 0) v->reverse_ctr--;
1580 /* handle crashed */
1581 if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1582 return RoadVehIsCrashed(v);
1585 /* road vehicle has broken down? */
1586 if (v->HandleBreakdown()) return true;
1587 if (v->vehstatus & VS_STOPPED) {
1588 v->SetLastSpeed();
1589 return true;
1592 ProcessOrders(v);
1593 v->HandleLoading();
1595 if (v->current_order.IsType(OT_LOADING)) return true;
1597 if (v->IsInDepot()) {
1598 /* Check if we should wait here for unbunching. */
1599 if (v->IsWaitingForUnbunching()) return true;
1600 if (RoadVehLeaveDepot(v, true)) return true;
1603 v->ShowVisualEffect();
1605 /* Check how far the vehicle needs to proceed */
1606 int j = v->UpdateSpeed();
1608 int adv_spd = v->GetAdvanceDistance();
1609 bool blocked = false;
1610 while (j >= adv_spd) {
1611 j -= adv_spd;
1613 RoadVehicle *u = v;
1614 for (RoadVehicle *prev = nullptr; u != nullptr; prev = u, u = u->Next()) {
1615 if (!IndividualRoadVehicleController(u, prev)) {
1616 blocked = true;
1617 break;
1620 if (blocked) break;
1622 /* Determine distance to next map position */
1623 adv_spd = v->GetAdvanceDistance();
1625 /* Test for a collision, but only if another movement will occur. */
1626 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1629 v->SetLastSpeed();
1631 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1632 if ((u->vehstatus & VS_HIDDEN) != 0) continue;
1634 u->UpdateViewport(false, false);
1637 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1638 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1639 * on next tick to discover whether it is still blocked. */
1640 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1642 return true;
1645 Money RoadVehicle::GetRunningCost() const
1647 const Engine *e = this->GetEngine();
1648 if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1650 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1651 if (cost_factor == 0) return 0;
1653 return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1656 bool RoadVehicle::Tick()
1658 PerformanceAccumulator framerate(PFE_GL_ROADVEHS);
1660 this->tick_counter++;
1662 if (this->IsFrontEngine()) {
1663 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
1664 return RoadVehController(this);
1667 return true;
1670 void RoadVehicle::SetDestTile(TileIndex tile)
1672 if (tile == this->dest_tile) return;
1673 this->path.clear();
1674 this->dest_tile = tile;
1677 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1679 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1680 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1681 if (v->IsChainInDepot()) {
1682 VehicleServiceInDepot(v);
1683 return;
1686 uint max_penalty;
1687 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1688 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1689 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1690 default: NOT_REACHED();
1693 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1694 /* Only go to the depot if it is not too far out of our way. */
1695 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1696 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1697 /* If we were already heading for a depot but it has
1698 * suddenly moved farther away, we continue our normal
1699 * schedule? */
1700 v->current_order.MakeDummy();
1701 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1703 return;
1706 DepotID depot = GetDepotIndex(rfdd.tile);
1708 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1709 v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS &&
1710 !Chance16(1, 20)) {
1711 return;
1714 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1715 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
1716 v->SetDestTile(rfdd.tile);
1717 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1720 /** Calandar day handler */
1721 void RoadVehicle::OnNewCalendarDay()
1723 if (!this->IsFrontEngine()) return;
1724 AgeVehicle(this);
1727 /** Economy day handler. */
1728 void RoadVehicle::OnNewEconomyDay()
1730 if (!this->IsFrontEngine()) return;
1732 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1733 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1735 CheckIfRoadVehNeedsService(this);
1737 CheckOrders(this);
1739 if (this->running_ticks == 0) return;
1741 CommandCost cost(EXPENSES_ROADVEH_RUN, this->GetRunningCost() * this->running_ticks / (CalendarTime::DAYS_IN_YEAR * Ticks::DAY_TICKS));
1743 this->profit_this_year -= cost.GetCost();
1744 this->running_ticks = 0;
1746 SubtractMoneyFromCompanyFract(this->owner, cost);
1748 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
1749 SetWindowClassesDirty(WC_ROADVEH_LIST);
1752 Trackdir RoadVehicle::GetVehicleTrackdir() const
1754 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1756 if (this->IsInDepot()) {
1757 /* We'll assume the road vehicle is facing outwards */
1758 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1761 if (IsBayRoadStopTile(this->tile)) {
1762 /* We'll assume the road vehicle is facing outwards */
1763 return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1766 /* Drive through road stops / wormholes (tunnels) */
1767 if (this->state > RVSB_TRACKDIR_MASK) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
1769 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1770 * otherwise transform it into a valid track direction */
1771 return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);
1774 uint16_t RoadVehicle::GetMaxWeight() const
1776 uint16_t weight = CargoSpec::Get(this->cargo_type)->WeightOfNUnits(this->GetEngine()->DetermineCapacity(this));
1778 /* Vehicle weight is not added for articulated parts. */
1779 if (!this->IsArticulatedPart()) {
1780 /* Road vehicle weight is in units of 1/4 t. */
1781 weight += GetVehicleProperty(this, PROP_ROADVEH_WEIGHT, RoadVehInfo(this->engine_type)->weight) / 4;
1784 return weight;