Update readme.md
[openttd-joker.git] / src / roadveh_cmd.cpp
blob6302948fecc0a6a24d783bd13f9cc604a026a3df
1 /* $Id$ */
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 */
10 /** @file roadveh_cmd.cpp Handling of road vehicles. */
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"
39 #include "table/strings.h"
41 #include "safeguards.h"
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
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
64 assert_compile(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder));
66 template <>
67 bool IsValidImageIndex<VEH_ROAD>(uint8 image_index)
69 return image_index < lengthof(_roadveh_images);
72 static const Trackdir _road_reverse_table[DIAGDIR_END] = {
73 TRACKDIR_RVREV_NE, TRACKDIR_RVREV_SE, TRACKDIR_RVREV_SW, TRACKDIR_RVREV_NW
76 /**
77 * Check whether a roadvehicle is a bus
78 * @return true if bus
80 bool RoadVehicle::IsBus() const
82 assert(this->IsFrontEngine());
83 return IsCargoInClass(this->cargo_type, CC_PASSENGERS);
86 /**
87 * Get the width of a road vehicle image in the GUI.
88 * @param offset Additional offset for positioning the sprite; set to nullptr if not needed
89 * @return Width in pixels
91 int RoadVehicle::GetDisplayImageWidth(Point *offset) const
93 int reference_width = ROADVEHINFO_DEFAULT_VEHICLE_WIDTH;
95 if (offset != nullptr) {
96 offset->x = ScaleGUITrad(reference_width) / 2;
97 offset->y = 0;
99 return ScaleGUITrad(this->gcache.cached_veh_length * reference_width / VEHICLE_LENGTH);
102 static void GetRoadVehIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
104 const Engine *e = Engine::Get(engine);
105 uint8 spritenum = e->u.road.image_index;
107 if (is_custom_sprite(spritenum)) {
108 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
109 if (result->IsValid()) return;
111 spritenum = e->original_image_index;
114 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
115 result->Set(DIR_W + _roadveh_images[spritenum]);
118 void RoadVehicle::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
120 uint8 spritenum = this->spritenum;
122 if (is_custom_sprite(spritenum)) {
123 GetCustomVehicleSprite(this, (Direction)(direction + 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum)), image_type, result);
124 if (result->IsValid()) return;
126 spritenum = this->GetEngine()->original_image_index;
129 assert(IsValidImageIndex<VEH_ROAD>(spritenum));
130 SpriteID sprite = direction + _roadveh_images[spritenum];
132 if (this->cargo.StoredCount() >= this->cargo_cap / 2U) sprite += _roadveh_full_adder[spritenum];
134 result->Set(sprite);
138 * Draw a road vehicle engine.
139 * @param left Left edge to draw within.
140 * @param right Right edge to draw within.
141 * @param preferred_x Preferred position of the engine.
142 * @param y Vertical position of the engine.
143 * @param engine Engine to draw
144 * @param pal Palette to use.
146 void DrawRoadVehEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
148 VehicleSpriteSeq seq;
149 GetRoadVehIcon(engine, image_type, &seq);
151 Rect16 rect = seq.GetBounds();
152 preferred_x = Clamp(preferred_x,
153 left - UnScaleGUI(rect.left),
154 right - UnScaleGUI(rect.right));
156 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
160 * Get the size of the sprite of a road vehicle sprite heading west (used for lists).
161 * @param engine The engine to get the sprite from.
162 * @param[out] width The width of the sprite.
163 * @param[out] height The height of the sprite.
164 * @param[out] xoffs Number of pixels to shift the sprite to the right.
165 * @param[out] yoffs Number of pixels to shift the sprite downwards.
166 * @param image_type Context the sprite is used in.
168 void GetRoadVehSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
170 VehicleSpriteSeq seq;
171 GetRoadVehIcon(engine, image_type, &seq);
173 Rect16 rect = seq.GetBounds();
175 width = UnScaleGUI(rect.right - rect.left + 1);
176 height = UnScaleGUI(rect.bottom - rect.top + 1);
177 xoffs = UnScaleGUI(rect.left);
178 yoffs = UnScaleGUI(rect.top);
182 * Get length of a road vehicle.
183 * @param v Road vehicle to query length.
184 * @return Length of the given road vehicle.
186 static uint GetRoadVehLength(const RoadVehicle *v)
188 const Engine *e = v->GetEngine();
189 uint length = VEHICLE_LENGTH;
191 uint16 veh_len = CALLBACK_FAILED;
192 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
193 /* Use callback 36 */
194 veh_len = GetVehicleProperty(v, PROP_ROADVEH_SHORTEN_FACTOR, CALLBACK_FAILED);
195 if (veh_len != CALLBACK_FAILED && veh_len >= VEHICLE_LENGTH) ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LENGTH, veh_len);
196 } else {
197 /* Use callback 11 */
198 veh_len = GetVehicleCallback(CBID_VEHICLE_LENGTH, 0, 0, v->engine_type, v);
200 if (veh_len == CALLBACK_FAILED) veh_len = e->u.road.shorten_factor;
201 if (veh_len != 0) {
202 length -= Clamp(veh_len, 0, VEHICLE_LENGTH - 1);
205 return length;
209 * Update the cache of a road vehicle.
210 * @param v Road vehicle needing an update of its cache.
211 * @param same_length should length of vehicles stay the same?
212 * @pre \a v must be first road vehicle.
214 void RoadVehUpdateCache(RoadVehicle *v, bool same_length)
216 assert(v->type == VEH_ROAD);
217 assert(v->IsFrontEngine());
219 v->InvalidateNewGRFCacheOfChain();
221 v->gcache.cached_total_length = 0;
223 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
224 /* Check the v->first cache. */
225 assert(u->First() == v);
227 /* Update the 'first engine' */
228 u->gcache.first_engine = (v == u) ? INVALID_ENGINE : v->engine_type;
230 /* Update the length of the vehicle. */
231 uint veh_len = GetRoadVehLength(u);
232 /* Verify length hasn't changed. */
233 if (same_length && veh_len != u->gcache.cached_veh_length) VehicleLengthChanged(u);
235 u->gcache.cached_veh_length = veh_len;
236 v->gcache.cached_total_length += u->gcache.cached_veh_length;
238 /* Update visual effect */
239 u->UpdateVisualEffect();
241 /* Update cargo aging period. */
242 u->vcache.cached_cargo_age_period = GetVehicleProperty(u, PROP_ROADVEH_CARGO_AGE_PERIOD, EngInfo(u->engine_type)->cargo_age_period);
245 uint max_speed = GetVehicleProperty(v, PROP_ROADVEH_SPEED, 0);
246 v->vcache.cached_max_speed = (max_speed != 0) ? max_speed * 4 : RoadVehInfo(v->engine_type)->max_speed;
250 * Build a road vehicle.
251 * @param tile tile of the depot where road vehicle is built.
252 * @param flags type of operation.
253 * @param e the engine to build.
254 * @param data unused.
255 * @param ret[out] the vehicle that has been built.
256 * @return the cost of this operation or an error.
258 CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
260 /* Check that the vehicle can drive on the road in question */
261 RoadTypeIdentifier rtid = e->GetRoadType();
262 const RoadtypeInfo *rti = GetRoadTypeInfo(rtid);
263 if (!HasTileAnyRoadSubType(tile, rtid.basetype, rti->powered_roadtypes)) return CommandError(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE);
265 if (flags & DC_EXEC) {
266 const RoadVehicleInfo *rvi = &e->u.road;
268 RoadVehicle *v = new RoadVehicle();
269 *ret = v;
270 v->direction = DiagDirToDir(GetRoadDepotDirection(tile));
271 v->owner = _current_company;
273 v->tile = tile;
274 int x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
275 int y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
276 v->x_pos = x;
277 v->y_pos = y;
278 v->z_pos = GetSlopePixelZ(x, y);
280 v->state = RVSB_IN_DEPOT;
281 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
283 v->spritenum = rvi->image_index;
284 v->cargo_type = e->GetDefaultCargoType();
285 v->cargo_cap = rvi->capacity;
286 v->refit_cap = 0;
288 v->last_station_visited = INVALID_STATION;
289 v->last_loading_station = INVALID_STATION;
290 v->engine_type = e->index;
291 v->gcache.first_engine = INVALID_ENGINE; // needs to be set before first callback
293 v->reliability = e->reliability;
294 v->reliability_spd_dec = e->reliability_spd_dec;
295 v->max_age = e->GetLifeLengthInDays();
296 _new_vehicle_id = v->index;
298 v->SetServiceInterval(Company::Get(v->owner)->settings.vehicle.servint_roadveh);
300 v->date_of_last_service = _date;
301 v->build_year = _cur_year;
303 v->sprite_seq.Set(SPR_IMG_QUERY);
304 v->random_bits = VehicleRandomBits();
305 v->SetFrontEngine();
307 v->rtid = rtid;
308 v->compatible_subtypes = rti->powered_roadtypes;
309 v->gcache.cached_veh_length = VEHICLE_LENGTH;
311 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
312 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
314 AddArticulatedParts(v);
315 v->InvalidateNewGRFCacheOfChain();
317 /* Call various callbacks after the whole consist has been constructed */
318 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
319 u->cargo_cap = u->GetEngine()->DetermineCapacity(u);
320 u->refit_cap = 0;
321 v->InvalidateNewGRFCache();
322 u->InvalidateNewGRFCache();
324 RoadVehUpdateCache(v);
325 /* Initialize cached values for realistic acceleration. */
326 if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) v->CargoChanged();
328 v->UpdatePosition();
330 CheckConsistencyOfArticulatedVehicle(v);
333 return CommandCost();
336 static FindDepotData FindClosestRoadDepot(const RoadVehicle *v, int max_distance)
338 if (IsRoadDepotTile(v->tile)) return FindDepotData(v->tile, 0);
340 switch (_settings_game.pf.pathfinder_for_roadvehs) {
341 case VPF_NPF: return NPFRoadVehicleFindNearestDepot(v, max_distance);
342 case VPF_YAPF: return YapfRoadVehicleFindNearestDepot(v, max_distance);
344 default: NOT_REACHED();
348 bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
350 FindDepotData rfdd = FindClosestRoadDepot(this, 0);
351 if (rfdd.best_length == UINT_MAX) return false;
353 if (location != nullptr) *location = rfdd.tile;
354 if (destination != nullptr) *destination = GetDepotIndex(rfdd.tile);
356 return true;
360 * Turn a roadvehicle around.
361 * @param tile unused
362 * @param flags operation to perform
363 * @param p1 vehicle ID to turn
364 * @param p2 unused
365 * @param text unused
366 * @return the cost of this operation or an error
368 CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
370 RoadVehicle *v = RoadVehicle::GetIfValid(p1);
371 if (v == nullptr) return CommandError();
373 if (!v->IsPrimaryVehicle()) return CommandError();
375 CommandCost ret = CheckOwnership(v->owner);
376 if (ret.Failed()) return ret;
378 if ((v->vehstatus & VS_STOPPED) ||
379 (v->vehstatus & VS_CRASHED) ||
380 v->breakdown_ctr != 0 ||
381 v->overtaking != 0 ||
382 v->state == RVSB_WORMHOLE ||
383 v->IsInDepot() ||
384 v->current_order.IsType(OT_LOADING)) {
385 return CommandError();
388 if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) return CommandError();
390 if (IsTileType(v->tile, MP_TUNNELBRIDGE) && DirToDiagDir(v->direction) == GetTunnelBridgeDirection(v->tile)) return CommandError();
392 if (flags & DC_EXEC) v->reverse_ctr = 180;
394 return CommandCost();
398 void RoadVehicle::MarkDirty()
400 for (RoadVehicle *v = this; v != nullptr; v = v->Next()) {
401 v->colourmap = PAL_NONE;
402 v->UpdateViewport(true, false);
404 this->CargoChanged();
407 void RoadVehicle::UpdateDeltaXY(Direction direction)
409 static const int8 _delta_xy_table[8][10] = {
410 /* 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 */
411 {3, 3, -1, -1, 0, 0, -1, -1, -1, -1}, // N
412 {3, 7, -1, -3, 0, -1, 0, -1, 0, 0}, // NE
413 {3, 3, -1, -1, 0, 0, 1, -1, 1, -1}, // E
414 {7, 3, -3, -1, -1, 0, 0, 0, 1, 0}, // SE
415 {3, 3, -1, -1, 0, 0, 1, 1, 1, 1}, // S
416 {3, 7, -1, -3, 0, -1, 0, 0, 0, 1}, // SW
417 {3, 3, -1, -1, 0, 0, -1, 1, -1, 1}, // W
418 {7, 3, -3, -1, -1, 0, -1, 0, 0, 0}, // NW
421 int shorten = VEHICLE_LENGTH - this->gcache.cached_veh_length;
422 if (!IsDiagonalDirection(direction)) shorten >>= 1;
424 const int8 *bb = _delta_xy_table[direction];
425 this->x_bb_offs = bb[5] + bb[9] * shorten;
426 this->y_bb_offs = bb[4] + bb[8] * shorten;;
427 this->x_offs = bb[3];
428 this->y_offs = bb[2];
429 this->x_extent = bb[1] + bb[7] * shorten;
430 this->y_extent = bb[0] + bb[6] * shorten;
431 this->z_extent = 6;
435 * Calculates the maximum speed of the vehicle under its current conditions.
436 * @return Maximum speed of the vehicle.
438 inline int RoadVehicle::GetCurrentMaxSpeed() const
440 int max_speed = this->gcache.cached_max_track_speed;
442 /* Limit speed to 50% while reversing, 75% in curves. */
443 for (const RoadVehicle *u = this; u != nullptr; u = u->Next()) {
444 if (_settings_game.vehicle.roadveh_acceleration_model == AM_REALISTIC) {
445 if (this->state <= RVSB_TRACKDIR_MASK && IsReversingRoadTrackdir((Trackdir)this->state)) {
446 max_speed = this->gcache.cached_max_track_speed / 2;
447 break;
450 // Are we in a curve and should slow down?
451 if (((u->direction & 1) == 0) && _settings_game.vehicle.slow_road_vehicles_in_curves) {
452 max_speed = this->gcache.cached_max_track_speed * 3 / 4;
456 /* Vehicle is on the middle part of a bridge. */
457 if (u->state == RVSB_WORMHOLE && !(u->vehstatus & VS_HIDDEN)) {
458 max_speed = min(max_speed, GetBridgeSpec(GetBridgeType(u->tile))->speed * 2);
462 return min(max_speed, this->current_order.GetMaxSpeed() * 2);
466 * Delete last vehicle of a chain road vehicles.
467 * @param v First roadvehicle.
469 static void DeleteLastRoadVeh(RoadVehicle *v)
471 RoadVehicle *first = v->First();
472 Vehicle *u = v;
473 for (; v->Next() != nullptr; v = v->Next()) u = v;
474 u->SetNext(nullptr);
475 v->last_station_visited = first->last_station_visited; // for PreDestructor
477 /* Only leave the road stop when we're really gone. */
478 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
480 delete v;
483 static void RoadVehSetRandomDirection(RoadVehicle *v)
485 static const DirDiff delta[] = {
486 DIRDIFF_45LEFT, DIRDIFF_SAME, DIRDIFF_SAME, DIRDIFF_45RIGHT
489 do {
490 uint32 r = Random();
492 v->direction = ChangeDir(v->direction, delta[r & 3]);
493 v->UpdateViewport(true, true);
494 } while ((v = v->Next()) != nullptr);
498 * Road vehicle chain has crashed.
499 * @param v First roadvehicle.
500 * @return whether the chain still exists.
502 static bool RoadVehIsCrashed(RoadVehicle *v)
504 v->crashed_ctr++;
505 if (v->crashed_ctr == 2) {
506 CreateEffectVehicleRel(v, 4, 4, 8, EV_EXPLOSION_LARGE);
507 } else if (v->crashed_ctr <= 45) {
508 if ((v->tick_counter & 7) == 0) RoadVehSetRandomDirection(v);
509 } else if (v->crashed_ctr >= 2220 && !(v->tick_counter & 0x1F)) {
510 bool ret = v->Next() != nullptr;
511 DeleteLastRoadVeh(v);
512 return ret;
515 return true;
519 * Check routine whether a road and a train vehicle have collided.
520 * @param v %Train vehicle to test.
521 * @param data Road vehicle to test.
522 * @return %Train vehicle if the vehicles collided, else \c nullptr.
524 static Vehicle *EnumCheckRoadVehCrashTrain(Vehicle *v, void *data)
526 const Vehicle *u = (Vehicle*)data;
528 return (v->type == VEH_TRAIN &&
529 abs(v->z_pos - u->z_pos) <= 6 &&
530 abs(v->x_pos - u->x_pos) <= 4 &&
531 abs(v->y_pos - u->y_pos) <= 4) ? v : nullptr;
534 uint RoadVehicle::Crash(bool flooded)
536 uint pass = this->GroundVehicleBase::Crash(flooded);
537 if (this->IsFrontEngine()) {
538 pass += 1; // driver
540 /* If we're in a drive through road stop we ought to leave it */
541 if (IsInsideMM(this->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END)) {
542 RoadStop::GetByTile(this->tile, GetRoadStopType(this->tile))->Leave(this);
545 this->crashed_ctr = flooded ? 2000 : 1; // max 2220, disappear pretty fast when flooded
546 return pass;
549 static void RoadVehCrash(RoadVehicle *v)
551 uint pass = v->Crash();
553 AI::NewEvent(v->owner, new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
554 Game::NewEvent(new ScriptEventVehicleCrashed(v->index, v->tile, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING));
556 SetDParam(0, pass);
557 AddVehicleNewsItem(
558 (pass == 1) ?
559 STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER : STR_NEWS_ROAD_VEHICLE_CRASH,
560 NT_ACCIDENT,
561 v->index
564 ModifyStationRatingAround(v->tile, v->owner, -160, 22);
565 if (_settings_client.sound.disaster) SndPlayVehicleFx(SND_12_EXPLOSION, v);
568 static bool RoadVehCheckTrainCrash(RoadVehicle *v)
570 //for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
571 // if (u->state == RVSB_WORMHOLE) continue;
573 // TileIndex tile = u->tile;
575 // if (!IsLevelCrossingTile(tile)) continue;
577 // if (HasVehicleOnPosXY(v->x_pos, v->y_pos, u, EnumCheckRoadVehCrashTrain)) {
578 // RoadVehCrash(v);
579 // return true;
580 // }
583 return false;
586 TileIndex RoadVehicle::GetOrderStationLocation(StationID station)
588 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
590 const Station *st = Station::Get(station);
591 if (!CanVehicleUseStation(this, st)) {
592 /* There is no stop left at the station, so don't even TRY to go there */
593 this->IncrementRealOrderIndex();
594 return 0;
597 return st->xy;
600 static void StartRoadVehSound(const RoadVehicle *v)
602 if (!PlayVehicleSound(v, VSE_START)) {
603 SoundID s = RoadVehInfo(v->engine_type)->sfx;
604 if (s == SND_19_BUS_START_PULL_AWAY && (v->tick_counter & 3) == 0) {
605 s = SND_1A_BUS_START_PULL_AWAY_WITH_HORN;
607 SndPlayVehicleFx(s, v);
611 struct RoadVehFindData {
612 int x;
613 int y;
614 const Vehicle *veh;
615 Vehicle *best;
616 uint best_diff;
617 Direction dir;
620 static Vehicle *EnumCheckRoadVehClose(Vehicle *v, void *data)
622 static const int8 dist_x[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
623 static const int8 dist_y[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
625 RoadVehFindData *rvf = (RoadVehFindData*)data;
627 short x_diff = v->x_pos - rvf->x;
628 short y_diff = v->y_pos - rvf->y;
630 if (v->type == VEH_ROAD &&
631 !v->IsInDepot() &&
632 abs(v->z_pos - rvf->veh->z_pos) < 6 &&
633 v->direction == rvf->dir &&
634 rvf->veh->First() != v->First() &&
635 (dist_x[v->direction] >= 0 || (x_diff > dist_x[v->direction] && x_diff <= 0)) &&
636 (dist_x[v->direction] <= 0 || (x_diff < dist_x[v->direction] && x_diff >= 0)) &&
637 (dist_y[v->direction] >= 0 || (y_diff > dist_y[v->direction] && y_diff <= 0)) &&
638 (dist_y[v->direction] <= 0 || (y_diff < dist_y[v->direction] && y_diff >= 0))) {
639 uint diff = abs(x_diff) + abs(y_diff);
641 if (diff < rvf->best_diff || (diff == rvf->best_diff && v->index < rvf->best->index)) {
642 rvf->best = v;
643 rvf->best_diff = diff;
647 return nullptr;
650 static RoadVehicle *RoadVehFindCloseTo(RoadVehicle *v, int x, int y, Direction dir, bool update_blocked_ctr = true)
652 RoadVehFindData rvf;
653 RoadVehicle *front = v->First();
655 if (front->reverse_ctr != 0) return nullptr;
657 rvf.x = x;
658 rvf.y = y;
659 rvf.dir = dir;
660 rvf.veh = v;
661 rvf.best_diff = UINT_MAX;
663 if (front->state == RVSB_WORMHOLE) {
664 FindVehicleOnPos(v->tile, &rvf, EnumCheckRoadVehClose);
665 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v->tile), &rvf, EnumCheckRoadVehClose);
666 } else {
667 FindVehicleOnPosXY(x, y, &rvf, EnumCheckRoadVehClose);
670 /* This code protects a roadvehicle from being blocked for ever
671 * If more than 1480 / 74 days a road vehicle is blocked, it will
672 * drive just through it. The ultimate backup-code of TTD.
673 * It can be disabled. */
674 if (rvf.best_diff == UINT_MAX) {
675 front->blocked_ctr = 0;
676 return nullptr;
679 if (update_blocked_ctr && ++front->blocked_ctr > 1480) return nullptr;
681 return RoadVehicle::From(rvf.best);
685 * A road vehicle arrives at a station. If it is the first time, create a news item.
686 * @param v Road vehicle that arrived.
687 * @param st Station where the road vehicle arrived.
689 static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
691 if (v->IsBus()) {
692 /* Check if station was ever visited before */
693 if (!(st->had_vehicle_of_type & HVOT_BUS)) {
694 st->had_vehicle_of_type |= HVOT_BUS;
695 SetDParam(0, st->index);
696 AddVehicleNewsItem(
697 v->rtid.IsRoad() ? STR_NEWS_FIRST_BUS_ARRIVAL : STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL,
698 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
699 v->index,
700 st->index
702 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
703 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
705 } else {
706 /* Check if station was ever visited before */
707 if (!(st->had_vehicle_of_type & HVOT_TRUCK)) {
708 st->had_vehicle_of_type |= HVOT_TRUCK;
709 SetDParam(0, st->index);
710 AddVehicleNewsItem(
711 v->rtid.IsRoad() ? STR_NEWS_FIRST_TRUCK_ARRIVAL : STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL,
712 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
713 v->index,
714 st->index
716 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
717 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
723 * This function looks at the vehicle and updates its speed (cur_speed
724 * and subspeed) variables. Furthermore, it returns the distance that
725 * the vehicle can drive this tick. #Vehicle::GetAdvanceDistance() determines
726 * the distance to drive before moving a step on the map.
727 * @return distance to drive.
729 int RoadVehicle::UpdateSpeed()
731 switch (_settings_game.vehicle.roadveh_acceleration_model) {
732 default: NOT_REACHED();
733 case AM_ORIGINAL:
734 return this->DoUpdateSpeed(this->overtaking != 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
736 case AM_REALISTIC:
737 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking != 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE ? 0 : 4, this->GetCurrentMaxSpeed());
741 static Direction RoadVehGetNewDirection(const RoadVehicle *v, int x, int y)
743 static const Direction _roadveh_new_dir[] = {
744 DIR_N , DIR_NW, DIR_W , INVALID_DIR,
745 DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
746 DIR_E , DIR_SE, DIR_S
749 x = x - v->x_pos + 1;
750 y = y - v->y_pos + 1;
752 if ((uint)x > 2 || (uint)y > 2) return v->direction;
753 return _roadveh_new_dir[y * 4 + x];
756 static Direction RoadVehGetSlidingDirection(const RoadVehicle *v, int x, int y)
758 Direction new_dir = RoadVehGetNewDirection(v, x, y);
759 Direction old_dir = v->direction;
760 DirDiff delta;
762 if (new_dir == old_dir) return old_dir;
763 delta = (DirDifference(new_dir, old_dir) > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
764 return ChangeDir(old_dir, delta);
767 struct OvertakeData {
768 const RoadVehicle *u;
769 const RoadVehicle *v;
770 TileIndex tile;
771 Trackdir trackdir;
774 static Vehicle *EnumFindVehBlockingOvertake(Vehicle *v, void *data)
776 const OvertakeData *od = (OvertakeData*)data;
778 return (v->type == VEH_ROAD && v->First() == v && v != od->u && v != od->v) ? v : nullptr;
781 static Vehicle *EnumFindVehPreventingOvertake(Vehicle *v, void *data)
783 const OvertakeData *od = (OvertakeData*)data;
785 Vehicle* blocking_v = EnumFindVehBlockingOvertake(v, data);
787 if (blocking_v == nullptr)
788 return nullptr;
790 if (blocking_v->type != VEH_ROAD)
791 return blocking_v;
793 RoadVehicle* blocking_road_v = RoadVehicle::From(blocking_v);
795 bool is_overtaking = (blocking_road_v->overtaking != 0);
796 bool is_driving_in_same_direction = (od->v->direction == blocking_road_v->direction);
797 bool has_lower_max_speed = (od->v->vcache.cached_max_speed > blocking_road_v->vcache.cached_max_speed);
798 bool has_been_stopped = (blocking_road_v->vehstatus & VS_STOPPED) != 0;
799 bool is_at_zero_speed = (blocking_road_v->cur_speed == 0);
800 bool is_straight_road_trackdir = IsStraightRoadTrackdir((Trackdir)(blocking_road_v->state & RVSB_TRACKDIR_MASK));
801 bool is_in_road_stop_or_station = (blocking_road_v->state >= RVSB_IN_ROAD_STOP) || IsTileType(blocking_road_v->tile, MP_STATION);
803 bool is_preventing = !is_driving_in_same_direction ||
804 is_overtaking ||
805 (!has_lower_max_speed && !(has_been_stopped || is_at_zero_speed)) ||
806 !is_straight_road_trackdir ||
807 is_in_road_stop_or_station;
809 return is_preventing ? blocking_v : nullptr;
813 * Check if overtaking is possible on a piece of track
815 * @param od Information about the tile and the involved vehicles
816 * @return true if we have to abort overtaking
818 static bool CheckRoadBlockedForOvertaking(OvertakeData *od)
820 if (!HasTileAnyRoadSubType(od->tile, od->v->rtid.basetype, od->v->compatible_subtypes)) return true;
821 TrackStatus ts = GetTileTrackStatus(od->tile, TRANSPORT_ROAD, od->v->rtid.basetype);
822 TrackdirBits trackdirbits = TrackStatusToTrackdirBits(ts);
823 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // barred level crossing
824 TrackBits trackbits = TrackdirBitsToTrackBits(trackdirbits);
826 /* Track does not continue along overtaking direction || track has junction || level crossing is barred */
827 bool track_does_continue = HasBit(trackdirbits, od->trackdir);
828 bool track_has_junction = (trackbits & ~TRACK_BIT_CROSS) != 0;
829 bool level_crossing_is_barred = (red_signals != TRACKDIR_BIT_NONE);
831 if (!track_does_continue || track_has_junction || level_crossing_is_barred) return true;
833 return HasVehicleOnPos(od->tile, od, EnumFindVehPreventingOvertake);
836 static void RoadVehCheckOvertake(RoadVehicle *v, RoadVehicle *u)
838 OvertakeData od;
840 od.v = v;
841 od.u = u;
843 bool has_lower_max_speed = (v->vcache.cached_max_speed > u->vcache.cached_max_speed);
844 bool has_been_stopped = (u->vehstatus & VS_STOPPED) != 0;
845 bool is_at_zero_speed = (u->cur_speed == 0);
847 if (!has_been_stopped && !is_at_zero_speed && !has_lower_max_speed) {
848 return;
851 /* Trams can't overtake other trams */
852 if (v->rtid.IsTram()) return;
854 /* Don't overtake in stations */
855 if (IsTileType(v->tile, MP_STATION) || IsTileType(u->tile, MP_STATION)) return;
857 /* For now, articulated road vehicles can't overtake anything. */
858 if (v->HasArticulatedPart()) return;
860 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
861 bool driving_in_same_direction = (v->direction == u->direction);
862 bool diagonal_direction = (v->direction & 1);
864 if (!driving_in_same_direction || !diagonal_direction) return;
866 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
867 bool is_straight_road_trackdir = IsStraightRoadTrackdir((Trackdir)(v->state & RVSB_TRACKDIR_MASK));
869 if (v->state >= RVSB_IN_ROAD_STOP || !is_straight_road_trackdir) return;
871 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
872 * accelerating, take the maximum speed for the comparison, else the current speed.
873 * Original acceleration always accelerates, so always use the maximum speed. */
874 int u_speed = (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL || u->GetAcceleration() > 0) ? u->GetCurrentMaxSpeed() : u->cur_speed;
875 if (u_speed >= v->GetCurrentMaxSpeed() &&
876 !(u->vehstatus & VS_STOPPED) &&
877 u->cur_speed != 0) {
878 return;
881 od.trackdir = DiagDirToDiagTrackdir(DirToDiagDir(v->direction));
883 /* Are the current and the next tile suitable for overtaking?
884 * - Does the track continue along od.trackdir
885 * - No junctions
886 * - No barred level crossing
887 * - No other vehicles in the way
889 od.tile = u->tile;
890 if (CheckRoadBlockedForOvertaking(&od)) return;
892 od.tile = u->tile + TileOffsByDiagDir(DirToDiagDir(u->direction));
893 if (CheckRoadBlockedForOvertaking(&od)) return;
895 /* When the vehicle in front of us is stopped we may only take
896 * half the time to pass it than when the vehicle is moving. */
897 v->overtaking_ctr = ((od.u->cur_speed == 0) || (od.u->vehstatus & VS_STOPPED)) ?
898 (RV_OVERTAKE_TIMEOUT / 2) :
900 v->overtaking = RVSB_DRIVE_SIDE;
903 static void RoadZPosAffectSpeed(RoadVehicle *v, int old_z)
905 if (old_z == v->z_pos || _settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) return;
907 if (old_z < v->z_pos) {
908 v->cur_speed = v->cur_speed * 232 / 256; // slow down by ~10%
909 } else {
910 uint16 spd = v->cur_speed + 2;
911 if (spd <= v->gcache.cached_max_track_speed) v->cur_speed = spd;
915 static int PickRandomBit(uint bits)
917 uint i;
918 uint num = RandomRange(CountBits(bits));
920 for (i = 0; !(bits & 1) || (int)--num >= 0; bits >>= 1, i++) {}
921 return i;
925 * Returns direction to for a road vehicle to take or
926 * INVALID_TRACKDIR if the direction is currently blocked
927 * @param v the Vehicle to do the pathfinding for
928 * @param tile the where to start the pathfinding
929 * @param enterdir the direction the vehicle enters the tile from
930 * @return the Trackdir to take
932 static Trackdir RoadFindPathToDest(RoadVehicle *v, TileIndex tile, DiagDirection enterdir)
934 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
936 TileIndex desttile;
937 Trackdir best_track;
938 bool path_found = true;
940 TrackStatus ts = GetTileTrackStatus(tile, TRANSPORT_ROAD, v->rtid.basetype);
941 TrackdirBits red_signals = TrackStatusToRedSignals(ts); // crossing
942 TrackdirBits trackdirs = TrackStatusToTrackdirBits(ts);
944 if (IsTileType(tile, MP_ROAD)) {
945 if (IsRoadDepot(tile) && (!IsTileOwner(tile, v->owner) || GetRoadDepotDirection(tile) == enterdir)) {
946 /* Road depot owned by another company or with the wrong orientation */
947 trackdirs = TRACKDIR_BIT_NONE;
949 } else if (IsTileType(tile, MP_STATION) && IsStandardRoadStopTile(tile)) {
950 /* Standard road stop (drive-through stops are treated as normal road) */
952 if (!IsTileOwner(tile, v->owner) || GetRoadStopDir(tile) == enterdir || v->HasArticulatedPart()) {
953 /* different station owner or wrong orientation or the vehicle has articulated parts */
954 trackdirs = TRACKDIR_BIT_NONE;
955 } else {
956 /* Our station */
957 RoadStopType rstype = v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK;
959 if (GetRoadStopType(tile) != rstype) {
960 /* Wrong station type */
961 trackdirs = TRACKDIR_BIT_NONE;
962 } else {
963 /* Proper station type, check if there is free loading bay */
964 if (!_settings_game.pf.roadveh_queue && IsStandardRoadStopTile(tile) &&
965 !RoadStop::GetByTile(tile, rstype)->HasFreeBay()) {
966 /* Station is full and RV queuing is off */
967 trackdirs = TRACKDIR_BIT_NONE;
972 /* The above lookups should be moved to GetTileTrackStatus in the
973 * future, but that requires more changes to the pathfinder and other
974 * stuff, probably even more arguments to GTTS.
977 /* Remove tracks unreachable from the enter dir */
978 trackdirs &= DiagdirReachesTrackdirs(enterdir);
979 if (trackdirs == TRACKDIR_BIT_NONE) {
980 /* No reachable tracks, so we'll reverse */
981 return_track(_road_reverse_table[enterdir]);
984 if (v->reverse_ctr != 0) {
985 bool reverse = true;
986 if (v->rtid.IsTram()) {
987 /* Trams may only reverse on a tile if it contains at least the straight
988 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
989 RoadBits rb = GetAnyRoadBits(tile, ROADTYPE_TRAM);
990 RoadBits straight = AxisToRoadBits(DiagDirToAxis(enterdir));
991 reverse = ((rb & straight) == straight) ||
992 (rb == DiagDirToRoadBits(enterdir));
994 if (reverse) {
995 v->reverse_ctr = 0;
996 if (v->tile != tile) {
997 return_track(_road_reverse_table[enterdir]);
1002 desttile = v->dest_tile;
1003 if (desttile == 0) {
1004 /* We've got no destination, pick a random track */
1005 return_track(PickRandomBit(trackdirs));
1008 /* Only one track to choose between? */
1009 if (KillFirstBit(trackdirs) == TRACKDIR_BIT_NONE) {
1010 return_track(FindFirstBit2x64(trackdirs));
1013 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1014 case VPF_NPF: best_track = NPFRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
1015 case VPF_YAPF: best_track = YapfRoadVehicleChooseTrack(v, tile, enterdir, trackdirs, path_found); break;
1017 default: NOT_REACHED();
1019 v->HandlePathfindingResult(path_found);
1021 found_best_track:;
1023 if (HasBit(red_signals, best_track)) return INVALID_TRACKDIR;
1025 return best_track;
1028 struct RoadDriveEntry {
1029 byte x, y;
1032 #include "table/roadveh_movement.h"
1034 static bool RoadVehLeaveDepot(RoadVehicle *v, bool first)
1036 /* Don't leave unless v and following wagons are in the depot. */
1037 for (const RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1038 if (u->state != RVSB_IN_DEPOT || u->tile != v->tile) return false;
1041 DiagDirection dir = GetRoadDepotDirection(v->tile);
1042 v->direction = DiagDirToDir(dir);
1044 Trackdir tdir = DiagDirToDiagTrackdir(dir);
1045 const RoadDriveEntry *rdp = _road_drive_data[v->rtid.basetype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + tdir];
1047 int x = TileX(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].x & 0xF);
1048 int y = TileY(v->tile) * TILE_SIZE + (rdp[RVC_DEPOT_START_FRAME].y & 0xF);
1050 if (first) {
1051 /* We are leaving a depot, but have to go to the exact same one; re-enter */
1052 if (v->current_order.IsType(OT_GOTO_DEPOT) && v->tile == v->dest_tile) {
1053 VehicleEnterDepot(v);
1054 return true;
1057 if (RoadVehFindCloseTo(v, x, y, v->direction, false) != nullptr) return true;
1059 VehicleServiceInDepot(v);
1061 StartRoadVehSound(v);
1063 /* Vehicle is about to leave a depot */
1064 v->cur_speed = 0;
1067 v->vehstatus &= ~VS_HIDDEN;
1068 v->state = tdir;
1069 v->frame = RVC_DEPOT_START_FRAME;
1071 v->x_pos = x;
1072 v->y_pos = y;
1073 v->UpdatePosition();
1074 v->UpdateInclination(true, true);
1076 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
1078 return true;
1081 static Trackdir FollowPreviousRoadVehicle(const RoadVehicle *v, const RoadVehicle *prev, TileIndex tile, DiagDirection entry_dir, bool already_reversed)
1083 if (prev->tile == v->tile && !already_reversed) {
1084 /* If the previous vehicle is on the same tile as this vehicle is
1085 * then it must have reversed. */
1086 return _road_reverse_table[entry_dir];
1089 byte prev_state = prev->state;
1090 Trackdir dir;
1092 if (prev_state == RVSB_WORMHOLE || prev_state == RVSB_IN_DEPOT) {
1093 DiagDirection diag_dir = INVALID_DIAGDIR;
1095 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
1096 diag_dir = GetTunnelBridgeDirection(tile);
1097 } else if (IsRoadDepotTile(tile)) {
1098 diag_dir = ReverseDiagDir(GetRoadDepotDirection(tile));
1101 if (diag_dir == INVALID_DIAGDIR) return INVALID_TRACKDIR;
1102 dir = DiagDirToDiagTrackdir(diag_dir);
1103 } else {
1104 if (already_reversed && prev->tile != tile) {
1106 * The vehicle has reversed, but did not go straight back.
1107 * It immediately turn onto another tile. This means that
1108 * the roadstate of the previous vehicle cannot be used
1109 * as the direction we have to go with this vehicle.
1111 * Next table is build in the following way:
1112 * - first row for when the vehicle in front went to the northern or
1113 * western tile, second for southern and eastern.
1114 * - columns represent the entry direction.
1115 * - cell values are determined by the Trackdir one has to take from
1116 * the entry dir (column) to the tile in north or south by only
1117 * going over the trackdirs used for turning 90 degrees, i.e.
1118 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1120 static const Trackdir reversed_turn_lookup[2][DIAGDIR_END] = {
1121 { TRACKDIR_UPPER_W, TRACKDIR_RIGHT_N, TRACKDIR_LEFT_N, TRACKDIR_UPPER_E },
1122 { TRACKDIR_RIGHT_S, TRACKDIR_LOWER_W, TRACKDIR_LOWER_E, TRACKDIR_LEFT_S }};
1123 dir = reversed_turn_lookup[prev->tile < tile ? 0 : 1][ReverseDiagDir(entry_dir)];
1124 } else if (HasBit(prev_state, RVS_IN_DT_ROAD_STOP)) {
1125 dir = (Trackdir)(prev_state & RVSB_ROAD_STOP_TRACKDIR_MASK);
1126 } else if (prev_state < TRACKDIR_END) {
1127 dir = (Trackdir)prev_state;
1128 } else {
1129 return INVALID_TRACKDIR;
1133 /* Do some sanity checking. */
1134 static const RoadBits required_roadbits[] = {
1135 ROAD_X, ROAD_Y, ROAD_NW | ROAD_NE, ROAD_SW | ROAD_SE,
1136 ROAD_NW | ROAD_SW, ROAD_NE | ROAD_SE, ROAD_X, ROAD_Y
1138 RoadBits required = required_roadbits[dir & 0x07];
1140 if ((required & GetAnyRoadBits(tile, v->rtid.basetype, false)) == ROAD_NONE) {
1141 dir = INVALID_TRACKDIR;
1144 return dir;
1148 * Can a tram track build without destruction on the given tile?
1149 * @param c the company that would be building the tram tracks
1150 * @param t the tile to build on.
1151 * @param rtid the tram type to build.
1152 * @param r the road bits needed.
1153 * @return true when a track track can be build on 't'
1155 static bool CanBuildTramTrackOnTile(CompanyID c, TileIndex t, RoadTypeIdentifier rtid, RoadBits r)
1157 /* The 'current' company is not necessarily the owner of the vehicle. */
1158 Backup<CompanyByte> cur_company(_current_company, c, FILE_LINE);
1160 CommandCost ret = DoCommand(t, rtid.Pack() << 4 | r, 0, DC_NO_WATER, CMD_BUILD_ROAD);
1162 cur_company.Restore();
1163 return ret.Succeeded();
1166 bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev)
1168 if (v->overtaking != 0) {
1169 if (IsTileType(v->tile, MP_STATION)) {
1170 /* Force us to be not overtaking! */
1171 v->overtaking = 0;
1172 } else if (++v->overtaking_ctr >= RV_OVERTAKE_TIMEOUT) {
1173 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1174 * if the vehicle started a corner. To protect that, only allow an abort of
1175 * overtake if we are on straight roads */
1176 if (v->state < RVSB_IN_ROAD_STOP && IsStraightRoadTrackdir((Trackdir)v->state)) {
1177 v->overtaking = 0;
1182 /* If this vehicle is in a depot and we've reached this point it must be
1183 * one of the articulated parts. It will stay in the depot until activated
1184 * by the previous vehicle in the chain when it gets to the right place. */
1185 if (v->IsInDepot()) return true;
1187 bool no_advance_tile = false;
1189 if (v->state == RVSB_WORMHOLE) {
1190 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1191 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
1193 if (v->IsFrontEngine()) {
1194 const Vehicle *u = RoadVehFindCloseTo(v, gp.x, gp.y, v->direction);
1195 if (u != nullptr) {
1196 v->cur_speed = u->First()->cur_speed;
1197 return false;
1201 if (IsTileType(gp.new_tile, MP_TUNNELBRIDGE) && HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
1203 if (IsRoadCustomBridgeHeadTile(gp.new_tile)) {
1204 v->frame = 15;
1205 no_advance_tile = true;
1206 } else {
1207 /* Vehicle has just entered a bridge or tunnel */
1208 v->x_pos = gp.x;
1209 v->y_pos = gp.y;
1210 v->UpdatePosition();
1211 v->UpdateInclination(true, true);
1212 return true;
1214 } else {
1215 v->x_pos = gp.x;
1216 v->y_pos = gp.y;
1217 v->UpdatePosition();
1218 RoadZPosAffectSpeed(v, v->UpdateInclination(false, false, true));
1219 if (v->IsDrawn()) v->Vehicle::UpdateViewport(true);
1220 return true;
1224 /* Get move position data for next frame.
1225 * For a drive-through road stop use 'straight road' move data.
1226 * In this case v->state is masked to give the road stop entry direction. */
1227 RoadDriveEntry rd = _road_drive_data[v->rtid.basetype][(
1228 (HasBit(v->state, RVS_IN_DT_ROAD_STOP) ? v->state & RVSB_ROAD_STOP_TRACKDIR_MASK : v->state) +
1229 (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking][v->frame + 1];
1231 if (rd.x & RDE_NEXT_TILE) {
1232 TileIndex tile = v->tile;
1233 if (!no_advance_tile) tile += TileOffsByDiagDir(static_cast<DiagDirection>(rd.x & 3));
1234 Trackdir dir;
1236 if (v->IsFrontEngine()) {
1237 /* If this is the front engine, look for the right path. */
1238 if (HasTileAnyRoadSubType(tile, v->rtid.basetype, v->compatible_subtypes)) {
1239 dir = RoadFindPathToDest(v, tile, static_cast<DiagDirection>(rd.x & 3));
1240 } else {
1241 dir = _road_reverse_table[(DiagDirection)(rd.x & 3)];
1243 } else if (no_advance_tile) {
1244 /* Follow previous vehicle out of custom bridge wormhole */
1245 dir = static_cast<Trackdir>(prev->state);
1246 } else {
1247 dir = FollowPreviousRoadVehicle(v, prev, tile, static_cast<DiagDirection>(rd.x & 3), false);
1250 if (dir == INVALID_TRACKDIR) {
1251 if (!v->IsFrontEngine()) error("Disconnecting road vehicle.");
1252 v->cur_speed = 0;
1253 return false;
1256 again:
1257 uint start_frame = RVC_DEFAULT_START_FRAME;
1258 if (IsReversingRoadTrackdir(dir)) {
1259 /* When turning around we can't be overtaking. */
1260 v->overtaking = 0;
1262 if (no_advance_tile) {
1263 DEBUG(misc, 0, "Road vehicle attempted to turn around on a single road piece bridge head");
1266 /* Turning around */
1267 if (v->rtid.IsTram()) {
1268 /* Determine the road bits the tram needs to be able to turn around
1269 * using the 'big' corner loop. */
1270 RoadBits needed;
1271 switch (dir) {
1272 default: NOT_REACHED();
1273 case TRACKDIR_RVREV_NE: needed = ROAD_SW; break;
1274 case TRACKDIR_RVREV_SE: needed = ROAD_NW; break;
1275 case TRACKDIR_RVREV_SW: needed = ROAD_NE; break;
1276 case TRACKDIR_RVREV_NW: needed = ROAD_SE; break;
1278 auto tile_turn_ok = [&]() -> bool {
1279 if (IsNormalRoadTile(tile)) {
1280 return !HasRoadWorks(tile) && (needed & GetRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE &&
1281 HasTileAnyRoadSubType(tile, v->rtid.basetype, v->compatible_subtypes);
1282 } else if (IsRoadCustomBridgeHeadTile(tile)) {
1283 return (needed & GetCustomBridgeHeadRoadBits(tile, ROADTYPE_TRAM)) != ROAD_NONE &&
1284 HasTileAnyRoadSubType(tile, v->rtid.basetype, v->compatible_subtypes);
1286 } else {
1287 return false;
1290 if ((v->Previous() != nullptr && v->Previous()->tile == tile) || (v->IsFrontEngine() && tile_turn_ok())) {
1292 * Taking the 'big' corner for trams only happens when:
1293 * - The previous vehicle in this (articulated) tram chain is
1294 * already on the 'next' tile, we just follow them regardless of
1295 * anything. When it is NOT on the 'next' tile, the tram started
1296 * doing a reversing turn when the piece of tram track on the next
1297 * tile did not exist yet. Do not use the big tram loop as that is
1298 * going to cause the tram to split up.
1299 * - Or the front of the tram can drive over the next tile.
1301 } else if (!v->IsFrontEngine() || !CanBuildTramTrackOnTile(v->owner, tile, v->rtid, needed) || ((~needed & GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false)) == ROAD_NONE)) {
1303 * Taking the 'small' corner for trams only happens when:
1304 * - We are not the from vehicle of an articulated tram.
1305 * - Or when the company cannot build on the next tile.
1307 * The 'small' corner means that the vehicle is on the end of a
1308 * tram track and needs to start turning there. To do this properly
1309 * the tram needs to start at an offset in the tram turning 'code'
1310 * for 'big' corners. It furthermore does not go to the next tile,
1311 * so that needs to be fixed too.
1313 tile = v->tile;
1314 start_frame = RVC_TURN_AROUND_START_FRAME_SHORT_TRAM;
1315 } else {
1316 /* The company can build on the next tile, so wait till (s)he does. */
1317 v->cur_speed = 0;
1318 return false;
1320 } else if (IsNormalRoadTile(v->tile) && GetDisallowedRoadDirections(v->tile) != DRD_NONE) {
1321 v->cur_speed = 0;
1322 return false;
1323 } else {
1324 tile = v->tile;
1328 /* Get position data for first frame on the new tile */
1329 const RoadDriveEntry *rdp = _road_drive_data[v->rtid.basetype][(dir + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)) ^ v->overtaking];
1331 int x = TileX(tile) * TILE_SIZE + rdp[start_frame].x;
1332 int y = TileY(tile) * TILE_SIZE + rdp[start_frame].y;
1334 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1335 if (v->IsFrontEngine()) {
1336 Vehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1337 if (u != nullptr) {
1338 v->cur_speed = u->First()->cur_speed;
1339 return false;
1343 uint32 r = VehicleEnterTile(v, tile, x, y);
1344 if (HasBit(r, VETS_CANNOT_ENTER)) {
1345 if (!IsTileType(tile, MP_TUNNELBRIDGE)) {
1346 v->cur_speed = 0;
1347 return false;
1349 /* Try an about turn to re-enter the previous tile */
1350 dir = _road_reverse_table[rd.x & 3];
1351 goto again;
1354 if (IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) && IsTileType(v->tile, MP_STATION)) {
1355 if (IsReversingRoadTrackdir(dir) && IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1356 /* New direction is trying to turn vehicle around.
1357 * We can't turn at the exit of a road stop so wait.*/
1358 v->cur_speed = 0;
1359 return false;
1362 /* If we are a drive through road stop and the next tile is of
1363 * the same road stop and the next tile isn't this one (i.e. we
1364 * are not reversing), then keep the reservation and state.
1365 * This way we will not be shortly unregister from the road
1366 * stop. It also makes it possible to load when on the edge of
1367 * two road stops; otherwise you could get vehicles that should
1368 * be loading but are not actually loading. */
1369 if (IsDriveThroughStopTile(v->tile) &&
1370 RoadStop::IsDriveThroughRoadStopContinuation(v->tile, tile) &&
1371 v->tile != tile) {
1372 /* So, keep 'our' state */
1373 dir = (Trackdir)v->state;
1374 } else if (IsRoadStop(v->tile)) {
1375 /* We're not continuing our drive through road stop, so leave. */
1376 RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile))->Leave(v);
1380 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
1381 TileIndex old_tile = v->tile;
1383 v->tile = tile;
1384 v->state = (byte)dir;
1385 v->frame = start_frame;
1386 if (GetRoadType(old_tile, v->rtid.basetype) != GetRoadType(tile, v->rtid.basetype)) {
1387 if (v->IsFrontEngine()) {
1388 RoadVehUpdateCache(v);
1390 v->First()->CargoChanged();
1393 if (new_dir != v->direction) {
1394 v->direction = new_dir;
1395 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1397 v->x_pos = x;
1398 v->y_pos = y;
1399 v->UpdatePosition();
1400 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1401 return true;
1404 if (rd.x & RDE_TURNED) {
1405 /* Vehicle has finished turning around, it will now head back onto the same tile */
1406 Trackdir dir;
1407 uint turn_around_start_frame = RVC_TURN_AROUND_START_FRAME;
1409 if (v->rtid.IsTram() && !IsRoadDepotTile(v->tile) && HasExactlyOneBit(GetAnyRoadBits(v->tile, ROADTYPE_TRAM, false))) {
1411 * The tram is turning around with one tram 'roadbit'. This means that
1412 * it is using the 'big' corner 'drive data'. However, to support the
1413 * trams to take a small corner, there is a 'turned' marker in the middle
1414 * of the turning 'drive data'. When the tram took the long corner, we
1415 * will still use the 'big' corner drive data, but we advance it one
1416 * frame. We furthermore set the driving direction so the turning is
1417 * going to be properly shown.
1419 turn_around_start_frame = RVC_START_FRAME_AFTER_LONG_TRAM;
1420 switch (rd.x & 0x3) {
1421 default: NOT_REACHED();
1422 case DIAGDIR_NW: dir = TRACKDIR_RVREV_SE; break;
1423 case DIAGDIR_NE: dir = TRACKDIR_RVREV_SW; break;
1424 case DIAGDIR_SE: dir = TRACKDIR_RVREV_NW; break;
1425 case DIAGDIR_SW: dir = TRACKDIR_RVREV_NE; break;
1427 } else {
1428 if (v->IsFrontEngine()) {
1429 /* If this is the front engine, look for the right path. */
1430 dir = RoadFindPathToDest(v, v->tile, (DiagDirection)(rd.x & 3));
1431 } else {
1432 dir = FollowPreviousRoadVehicle(v, prev, v->tile, (DiagDirection)(rd.x & 3), true);
1436 if (dir == INVALID_TRACKDIR) {
1437 v->cur_speed = 0;
1438 return false;
1441 const RoadDriveEntry *rdp = _road_drive_data[v->rtid.basetype][(_settings_game.vehicle.road_side << RVS_DRIVE_SIDE) + dir];
1443 int x = TileX(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].x;
1444 int y = TileY(v->tile) * TILE_SIZE + rdp[turn_around_start_frame].y;
1446 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1447 if (v->IsFrontEngine() && RoadVehFindCloseTo(v, x, y, new_dir) != nullptr) return false;
1449 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1450 if (HasBit(r, VETS_CANNOT_ENTER)) {
1451 v->cur_speed = 0;
1452 return false;
1455 v->state = dir;
1456 v->frame = turn_around_start_frame;
1458 if (new_dir != v->direction) {
1459 v->direction = new_dir;
1460 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1463 v->x_pos = x;
1464 v->y_pos = y;
1465 v->UpdatePosition();
1466 RoadZPosAffectSpeed(v, v->UpdateInclination(true, true));
1467 return true;
1470 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1471 * it's on a depot tile, check if it's time to activate the next vehicle in
1472 * the chain yet. */
1473 if (v->Next() != nullptr && IsRoadDepotTile(v->tile)) {
1474 if (v->frame == v->gcache.cached_veh_length + RVC_DEPOT_START_FRAME) {
1475 RoadVehLeaveDepot(v->Next(), false);
1479 /* Calculate new position for the vehicle */
1480 int x = (v->x_pos & ~15) + (rd.x & 15);
1481 int y = (v->y_pos & ~15) + (rd.y & 15);
1483 Direction new_dir = RoadVehGetSlidingDirection(v, x, y);
1485 if (v->IsFrontEngine() && !IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END)) {
1486 /* Vehicle is not in a road stop.
1487 * Check for another vehicle to overtake */
1488 RoadVehicle *u = RoadVehFindCloseTo(v, x, y, new_dir);
1490 if (u != nullptr) {
1491 u = u->First();
1492 /* There is a vehicle in front overtake it if possible */
1493 if (v->overtaking == 0) RoadVehCheckOvertake(v, u);
1494 if (v->overtaking == 0) v->cur_speed = u->cur_speed;
1496 /* In case an RV is stopped in a road stop, why not try to load? */
1497 if (v->cur_speed == 0 && 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) && !v->current_order.IsType(OT_LEAVESTATION) &&
1500 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK)) {
1501 Station *st = Station::GetByTile(v->tile);
1502 v->last_station_visited = st->index;
1503 RoadVehArrivesAt(v, st);
1504 v->BeginLoading();
1506 return false;
1510 Direction old_dir = v->direction;
1511 if (new_dir != old_dir) {
1512 v->direction = new_dir;
1513 if (_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) v->cur_speed -= v->cur_speed >> 2;
1515 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1516 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1517 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1518 * The short (inner) curve has 8 frames, this elongates it to 10. */
1519 v->UpdateInclination(false, true);
1520 return true;
1523 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1524 * if the vehicle is in a drive-through road stop and this is the destination station
1525 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1526 * (the station test and stop type test ensure that other vehicles, using the road stop as
1527 * a through route, do not stop) */
1528 if (v->IsFrontEngine() && ((IsInsideMM(v->state, RVSB_IN_ROAD_STOP, RVSB_IN_ROAD_STOP_END) &&
1529 _road_stop_stop_frame[v->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)] == v->frame) ||
1530 (IsInsideMM(v->state, RVSB_IN_DT_ROAD_STOP, RVSB_IN_DT_ROAD_STOP_END) &&
1531 v->current_order.ShouldStopAtStation(v, GetStationIndex(v->tile)) &&
1532 v->owner == GetTileOwner(v->tile) &&
1533 GetRoadStopType(v->tile) == (v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK) &&
1534 v->frame == RVC_DRIVE_THROUGH_STOP_FRAME))) {
1536 RoadStop *rs = RoadStop::GetByTile(v->tile, GetRoadStopType(v->tile));
1537 Station *st = Station::GetByTile(v->tile);
1539 /* Vehicle is at the stop position (at a bay) in a road stop.
1540 * Note, if vehicle is loading/unloading it has already been handled,
1541 * so if we get here the vehicle has just arrived or is just ready to leave. */
1542 if (!HasBit(v->state, RVS_ENTERED_STOP)) {
1543 /* Vehicle has arrived at a bay in a road stop */
1545 if (IsDriveThroughStopTile(v->tile)) {
1546 TileIndex next_tile = TILE_ADD(v->tile, TileOffsByDir(v->direction));
1548 /* Check if next inline bay is free and has compatible road. */
1549 if (RoadStop::IsDriveThroughRoadStopContinuation(v->tile, next_tile) && HasTileAnyRoadSubType(next_tile, v->rtid.basetype, v->compatible_subtypes)) {
1550 v->frame++;
1551 v->x_pos = x;
1552 v->y_pos = y;
1553 v->UpdatePosition();
1554 RoadZPosAffectSpeed(v, v->UpdateInclination(true, false));
1555 return true;
1559 rs->SetEntranceBusy(false);
1560 SetBit(v->state, RVS_ENTERED_STOP);
1562 v->last_station_visited = st->index;
1564 if (IsDriveThroughStopTile(v->tile) || (v->current_order.IsType(OT_GOTO_STATION) && v->current_order.GetDestination() == st->index)) {
1565 RoadVehArrivesAt(v, st);
1566 v->BeginLoading();
1567 return false;
1569 } else {
1570 /* Vehicle is ready to leave a bay in a road stop */
1571 if (rs->IsEntranceBusy()) {
1572 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1573 v->cur_speed = 0;
1574 return false;
1576 if (v->current_order.IsType(OT_LEAVESTATION)) v->current_order.Free();
1579 if (IsStandardRoadStopTile(v->tile)) rs->SetEntranceBusy(true);
1581 StartRoadVehSound(v);
1582 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1585 /* Check tile position conditions - i.e. stop position in depot,
1586 * entry onto bridge or into tunnel */
1587 uint32 r = VehicleEnterTile(v, v->tile, x, y);
1588 if (HasBit(r, VETS_CANNOT_ENTER)) {
1589 v->cur_speed = 0;
1590 return false;
1593 if (v->current_order.IsType(OT_LEAVESTATION) && IsDriveThroughStopTile(v->tile)) {
1594 v->current_order.Free();
1597 /* Move to next frame unless vehicle arrived at a stop position
1598 * in a depot or entered a tunnel/bridge */
1599 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) v->frame++;
1600 v->x_pos = x;
1601 v->y_pos = y;
1602 v->UpdatePosition();
1603 RoadZPosAffectSpeed(v, v->UpdateInclination(false, true, v->state == RVSB_WORMHOLE));
1604 return true;
1607 static bool RoadVehController(RoadVehicle *v)
1609 /* decrease counters */
1610 v->current_order_time++;
1611 if (v->reverse_ctr != 0) v->reverse_ctr--;
1613 /* handle crashed */
1614 if (v->vehstatus & VS_CRASHED || RoadVehCheckTrainCrash(v)) {
1615 return RoadVehIsCrashed(v);
1618 /* road vehicle has broken down? */
1619 if (v->HandleBreakdown()) return true;
1620 if (v->vehstatus & VS_STOPPED) return true;
1622 ProcessOrders(v);
1623 v->HandleLoading();
1625 if (v->current_order.IsType(OT_LOADING)) return true;
1626 v->HandleWaiting(false);
1627 if (v->current_order.IsType(OT_WAITING)) return true;
1629 if (v->IsInDepot() && RoadVehLeaveDepot(v, true)) return true;
1631 v->ShowVisualEffect();
1633 /* Check how far the vehicle needs to proceed */
1634 int j = v->UpdateSpeed();
1636 int adv_spd = v->GetAdvanceDistance();
1637 bool blocked = false;
1638 while (j >= adv_spd) {
1639 j -= adv_spd;
1641 RoadVehicle *u = v;
1642 for (RoadVehicle *prev = nullptr; u != nullptr; prev = u, u = u->Next()) {
1643 if (!IndividualRoadVehicleController(u, prev)) {
1644 blocked = true;
1645 break;
1648 if (blocked) break;
1650 /* Determine distance to next map position */
1651 adv_spd = v->GetAdvanceDistance();
1653 /* Test for a collision, but only if another movement will occur. */
1654 if (j >= adv_spd && RoadVehCheckTrainCrash(v)) break;
1657 v->SetLastSpeed();
1659 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
1660 if (!(u->IsDrawn())) continue;
1662 u->UpdateViewport(false, false);
1665 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1666 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1667 * on next tick to discover whether it is still blocked. */
1668 if (v->progress == 0) v->progress = blocked ? adv_spd - 1 : j;
1670 return true;
1673 Money RoadVehicle::GetRunningCost() const
1675 const Engine *e = this->GetEngine();
1676 if (e->u.road.running_cost_class == INVALID_PRICE) return 0;
1678 uint cost_factor = GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR, e->u.road.running_cost);
1679 if (cost_factor == 0) return 0;
1681 return GetPrice(e->u.road.running_cost_class, cost_factor, e->GetGRF());
1684 bool RoadVehicle::Tick()
1686 this->tick_counter++;
1688 if (this->IsFrontEngine()) {
1689 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot())) this->running_ticks++;
1690 return RoadVehController(this);
1693 return true;
1696 static void CheckIfRoadVehNeedsService(RoadVehicle *v)
1698 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1699 if (Company::Get(v->owner)->settings.vehicle.servint_roadveh == 0 || !v->NeedsAutomaticServicing()) return;
1700 if (v->IsChainInDepot()) {
1701 VehicleServiceInDepot(v);
1702 return;
1705 uint max_penalty;
1706 switch (_settings_game.pf.pathfinder_for_roadvehs) {
1707 case VPF_NPF: max_penalty = _settings_game.pf.npf.maximum_go_to_depot_penalty; break;
1708 case VPF_YAPF: max_penalty = _settings_game.pf.yapf.maximum_go_to_depot_penalty; break;
1709 default: NOT_REACHED();
1712 FindDepotData rfdd = FindClosestRoadDepot(v, max_penalty);
1713 /* Only go to the depot if it is not too far out of our way. */
1714 if (rfdd.best_length == UINT_MAX || rfdd.best_length > max_penalty) {
1715 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
1716 /* If we were already heading for a depot but it has
1717 * suddenly moved farther away, we continue our normal
1718 * schedule? */
1719 v->current_order.MakeDummy();
1720 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1722 return;
1725 DepotID depot = GetDepotIndex(rfdd.tile);
1727 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
1728 v->current_order.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS &&
1729 !Chance16(1, 20)) {
1730 return;
1733 SetBit(v->gv_flags, GVF_SUPPRESS_IMPLICIT_ORDERS);
1734 v->current_order.MakeGoToDepot(depot, ODTFB_SERVICE);
1735 v->dest_tile = rfdd.tile;
1736 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
1739 void RoadVehicle::OnNewDay()
1741 AgeVehicle(this);
1743 if (!this->IsFrontEngine()) return;
1745 if ((++this->day_counter & 7) == 0) DecreaseVehicleValue(this);
1746 if (this->blocked_ctr == 0) CheckVehicleBreakdown(this);
1748 CheckIfRoadVehNeedsService(this);
1750 CheckOrders(this);
1752 if (this->running_ticks == 0) return;
1754 CommandCost cost(EXPENSES_ROADVEH_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
1756 this->profit_this_year -= cost.GetCost();
1757 this->running_ticks = 0;
1759 SubtractMoneyFromCompanyFract(this->owner, cost);
1761 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
1762 SetWindowClassesDirty(WC_ROADVEH_LIST);
1765 Trackdir RoadVehicle::GetVehicleTrackdir() const
1767 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
1769 if (this->IsInDepot()) {
1770 /* We'll assume the road vehicle is facing outwards */
1771 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile));
1774 if (IsStandardRoadStopTile(this->tile)) {
1775 /* We'll assume the road vehicle is facing outwards */
1776 return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile)); // Road vehicle in a station
1779 /* Drive through road stops / wormholes (tunnels) */
1780 if (this->state > RVSB_TRACKDIR_MASK) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
1782 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1783 * otherwise transform it into a valid track direction */
1784 return (Trackdir)((IsReversingRoadTrackdir((Trackdir)this->state)) ? (this->state - 6) : this->state);