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/>.
10 /** @file roadveh_cmd.cpp Handling of road vehicles. */
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"
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"
37 #include "zoom_func.h"
38 #include "framerate_type.h"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 static const uint16 _roadveh_images
[] = {
45 0xCD4, 0xCDC, 0xCE4, 0xCEC, 0xCF4, 0xCFC, 0xD0C, 0xD14,
46 0xD24, 0xD1C, 0xD2C, 0xD04, 0xD1C, 0xD24, 0xD6C, 0xD74,
47 0xD7C, 0xC14, 0xC1C, 0xC24, 0xC2C, 0xC34, 0xC3C, 0xC4C,
48 0xC54, 0xC64, 0xC5C, 0xC6C, 0xC44, 0xC5C, 0xC64, 0xCAC,
49 0xCB4, 0xCBC, 0xD94, 0xD9C, 0xDA4, 0xDAC, 0xDB4, 0xDBC,
50 0xDCC, 0xDD4, 0xDE4, 0xDDC, 0xDEC, 0xDC4, 0xDDC, 0xDE4,
51 0xE2C, 0xE34, 0xE3C, 0xC14, 0xC1C, 0xC2C, 0xC3C, 0xC4C,
52 0xC5C, 0xC64, 0xC6C, 0xC74, 0xC84, 0xC94, 0xCA4
55 static const uint16 _roadveh_full_adder
[] = {
56 0, 88, 0, 0, 0, 0, 48, 48,
57 48, 48, 0, 0, 64, 64, 0, 16,
58 16, 0, 88, 0, 0, 0, 0, 48,
59 48, 48, 48, 0, 0, 64, 64, 0,
60 16, 16, 0, 88, 0, 0, 0, 0,
61 48, 48, 48, 48, 0, 0, 64, 64,
62 0, 16, 16, 0, 8, 8, 8, 8,
65 assert_compile(lengthof(_roadveh_images
) == lengthof(_roadveh_full_adder
));
68 bool IsValidImageIndex
<VEH_ROAD
>(uint8 image_index
)
70 return image_index
< lengthof(_roadveh_images
);
73 static const Trackdir _road_reverse_table
[DIAGDIR_END
] = {
74 TRACKDIR_RVREV_NE
, TRACKDIR_RVREV_SE
, TRACKDIR_RVREV_SW
, TRACKDIR_RVREV_NW
78 * Check whether a roadvehicle is a bus
81 bool RoadVehicle::IsBus() const
83 assert(this->IsFrontEngine());
84 return IsCargoInClass(this->cargo_type
, CC_PASSENGERS
);
88 * Get the width of a road vehicle image in the GUI.
89 * @param offset Additional offset for positioning the sprite; set to NULL if not needed
90 * @return Width in pixels
92 int RoadVehicle::GetDisplayImageWidth(Point
*offset
) const
94 int reference_width
= ROADVEHINFO_DEFAULT_VEHICLE_WIDTH
;
97 offset
->x
= ScaleGUITrad(reference_width
) / 2;
100 return ScaleGUITrad(this->gcache
.cached_veh_length
* reference_width
/ VEHICLE_LENGTH
);
103 static void GetRoadVehIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
105 const Engine
*e
= Engine::Get(engine
);
106 uint8 spritenum
= e
->u
.road
.image_index
;
108 if (is_custom_sprite(spritenum
)) {
109 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
110 if (result
->IsValid()) return;
112 spritenum
= e
->original_image_index
;
115 assert(IsValidImageIndex
<VEH_ROAD
>(spritenum
));
116 result
->Set(DIR_W
+ _roadveh_images
[spritenum
]);
119 void RoadVehicle::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
121 uint8 spritenum
= this->spritenum
;
123 if (is_custom_sprite(spritenum
)) {
124 GetCustomVehicleSprite(this, (Direction
)(direction
+ 4 * IS_CUSTOM_SECONDHEAD_SPRITE(spritenum
)), image_type
, result
);
125 if (result
->IsValid()) return;
127 spritenum
= this->GetEngine()->original_image_index
;
130 assert(IsValidImageIndex
<VEH_ROAD
>(spritenum
));
131 SpriteID sprite
= direction
+ _roadveh_images
[spritenum
];
133 if (this->cargo
.StoredCount() >= this->cargo_cap
/ 2U) sprite
+= _roadveh_full_adder
[spritenum
];
139 * Draw a road vehicle engine.
140 * @param left Left edge to draw within.
141 * @param right Right edge to draw within.
142 * @param preferred_x Preferred position of the engine.
143 * @param y Vertical position of the engine.
144 * @param engine Engine to draw
145 * @param pal Palette to use.
147 void DrawRoadVehEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
149 VehicleSpriteSeq seq
;
150 GetRoadVehIcon(engine
, image_type
, &seq
);
153 seq
.GetBounds(&rect
);
154 preferred_x
= Clamp(preferred_x
,
155 left
- UnScaleGUI(rect
.left
),
156 right
- UnScaleGUI(rect
.right
));
158 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
162 * Get the size of the sprite of a road vehicle sprite heading west (used for lists).
163 * @param engine The engine to get the sprite from.
164 * @param[out] width The width of the sprite.
165 * @param[out] height The height of the sprite.
166 * @param[out] xoffs Number of pixels to shift the sprite to the right.
167 * @param[out] yoffs Number of pixels to shift the sprite downwards.
168 * @param image_type Context the sprite is used in.
170 void GetRoadVehSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
172 VehicleSpriteSeq seq
;
173 GetRoadVehIcon(engine
, image_type
, &seq
);
176 seq
.GetBounds(&rect
);
178 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
179 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
180 xoffs
= UnScaleGUI(rect
.left
);
181 yoffs
= UnScaleGUI(rect
.top
);
185 * Get length of a road vehicle.
186 * @param v Road vehicle to query length.
187 * @return Length of the given road vehicle.
189 static uint
GetRoadVehLength(const RoadVehicle
*v
)
191 const Engine
*e
= v
->GetEngine();
192 uint length
= VEHICLE_LENGTH
;
194 uint16 veh_len
= CALLBACK_FAILED
;
195 if (e
->GetGRF() != NULL
&& e
->GetGRF()->grf_version
>= 8) {
196 /* Use callback 36 */
197 veh_len
= GetVehicleProperty(v
, PROP_ROADVEH_SHORTEN_FACTOR
, CALLBACK_FAILED
);
198 if (veh_len
!= CALLBACK_FAILED
&& veh_len
>= VEHICLE_LENGTH
) ErrorUnknownCallbackResult(e
->GetGRFID(), CBID_VEHICLE_LENGTH
, veh_len
);
200 /* Use callback 11 */
201 veh_len
= GetVehicleCallback(CBID_VEHICLE_LENGTH
, 0, 0, v
->engine_type
, v
);
203 if (veh_len
== CALLBACK_FAILED
) veh_len
= e
->u
.road
.shorten_factor
;
205 length
-= Clamp(veh_len
, 0, VEHICLE_LENGTH
- 1);
212 * Update the cache of a road vehicle.
213 * @param v Road vehicle needing an update of its cache.
214 * @param same_length should length of vehicles stay the same?
215 * @pre \a v must be first road vehicle.
217 void RoadVehUpdateCache(RoadVehicle
*v
, bool same_length
)
219 assert(v
->type
== VEH_ROAD
);
220 assert(v
->IsFrontEngine());
222 v
->InvalidateNewGRFCacheOfChain();
224 v
->gcache
.cached_total_length
= 0;
226 for (RoadVehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
227 /* Check the v->first cache. */
228 assert(u
->First() == v
);
230 /* Update the 'first engine' */
231 u
->gcache
.first_engine
= (v
== u
) ? INVALID_ENGINE
: v
->engine_type
;
233 /* Update the length of the vehicle. */
234 uint veh_len
= GetRoadVehLength(u
);
235 /* Verify length hasn't changed. */
236 if (same_length
&& veh_len
!= u
->gcache
.cached_veh_length
) VehicleLengthChanged(u
);
238 u
->gcache
.cached_veh_length
= veh_len
;
239 v
->gcache
.cached_total_length
+= u
->gcache
.cached_veh_length
;
241 /* Update visual effect */
242 u
->UpdateVisualEffect();
244 /* Update cargo aging period. */
245 u
->vcache
.cached_cargo_age_period
= GetVehicleProperty(u
, PROP_ROADVEH_CARGO_AGE_PERIOD
, EngInfo(u
->engine_type
)->cargo_age_period
);
248 uint max_speed
= GetVehicleProperty(v
, PROP_ROADVEH_SPEED
, 0);
249 v
->vcache
.cached_max_speed
= (max_speed
!= 0) ? max_speed
* 4 : RoadVehInfo(v
->engine_type
)->max_speed
;
253 * Build a road vehicle.
254 * @param tile tile of the depot where road vehicle is built.
255 * @param flags type of operation.
256 * @param e the engine to build.
257 * @param data unused.
258 * @param[out] ret the vehicle that has been built.
259 * @return the cost of this operation or an error.
261 CommandCost
CmdBuildRoadVehicle(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
263 if (HasTileRoadType(tile
, ROADTYPE_TRAM
) != HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
)) return_cmd_error(STR_ERROR_DEPOT_WRONG_DEPOT_TYPE
);
265 if (flags
& DC_EXEC
) {
266 const RoadVehicleInfo
*rvi
= &e
->u
.road
;
268 RoadVehicle
*v
= new RoadVehicle();
270 v
->direction
= DiagDirToDir(GetRoadDepotDirection(tile
));
271 v
->owner
= _current_company
;
274 int x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
275 int y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
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
;
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();
307 v
->roadtype
= HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
;
308 v
->compatible_roadtypes
= RoadTypeToRoadTypes(v
->roadtype
);
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
!= NULL
; u
= u
->Next()) {
319 u
->cargo_cap
= u
->GetEngine()->DetermineCapacity(u
);
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();
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
!= NULL
) *location
= rfdd
.tile
;
354 if (destination
!= NULL
) *destination
= GetDepotIndex(rfdd
.tile
);
360 * Turn a roadvehicle around.
362 * @param flags operation to perform
363 * @param p1 vehicle ID to turn
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
== NULL
) return CMD_ERROR
;
373 if (!v
->IsPrimaryVehicle()) return CMD_ERROR
;
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
||
384 v
->current_order
.IsType(OT_LOADING
)) {
388 if (IsNormalRoadTile(v
->tile
) && GetDisallowedRoadDirections(v
->tile
) != DRD_NONE
) return CMD_ERROR
;
390 if (IsTileType(v
->tile
, MP_TUNNELBRIDGE
) && DirToDiagDir(v
->direction
) == GetTunnelBridgeDirection(v
->tile
)) return CMD_ERROR
;
392 if (flags
& DC_EXEC
) v
->reverse_ctr
= 180;
394 return CommandCost();
398 void RoadVehicle::MarkDirty()
400 for (RoadVehicle
*v
= this; v
!= NULL
; v
= v
->Next()) {
401 v
->colourmap
= PAL_NONE
;
402 v
->UpdateViewport(true, false);
404 this->CargoChanged();
407 void RoadVehicle::UpdateDeltaXY()
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(this->direction
)) shorten
>>= 1;
424 const int8
*bb
= _delta_xy_table
[this->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
;
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->vcache
.cached_max_speed
;
442 /* Limit speed to 50% while reversing, 75% in curves. */
443 for (const RoadVehicle
*u
= this; u
!= NULL
; 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->vcache
.cached_max_speed
/ 2;
448 } else if ((u
->direction
& 1) == 0) {
449 max_speed
= this->vcache
.cached_max_speed
* 3 / 4;
453 /* Vehicle is on the middle part of a bridge. */
454 if (u
->state
== RVSB_WORMHOLE
&& !(u
->vehstatus
& VS_HIDDEN
)) {
455 max_speed
= min(max_speed
, GetBridgeSpec(GetBridgeType(u
->tile
))->speed
* 2);
459 return min(max_speed
, this->current_order
.GetMaxSpeed() * 2);
463 * Delete last vehicle of a chain road vehicles.
464 * @param v First roadvehicle.
466 static void DeleteLastRoadVeh(RoadVehicle
*v
)
468 RoadVehicle
*first
= v
->First();
470 for (; v
->Next() != NULL
; v
= v
->Next()) u
= v
;
472 v
->last_station_visited
= first
->last_station_visited
; // for PreDestructor
474 /* Only leave the road stop when we're really gone. */
475 if (IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
))->Leave(v
);
480 static void RoadVehSetRandomDirection(RoadVehicle
*v
)
482 static const DirDiff delta
[] = {
483 DIRDIFF_45LEFT
, DIRDIFF_SAME
, DIRDIFF_SAME
, DIRDIFF_45RIGHT
489 v
->direction
= ChangeDir(v
->direction
, delta
[r
& 3]);
490 v
->UpdateViewport(true, true);
491 } while ((v
= v
->Next()) != NULL
);
495 * Road vehicle chain has crashed.
496 * @param v First roadvehicle.
497 * @return whether the chain still exists.
499 static bool RoadVehIsCrashed(RoadVehicle
*v
)
502 if (v
->crashed_ctr
== 2) {
503 CreateEffectVehicleRel(v
, 4, 4, 8, EV_EXPLOSION_LARGE
);
504 } else if (v
->crashed_ctr
<= 45) {
505 if ((v
->tick_counter
& 7) == 0) RoadVehSetRandomDirection(v
);
506 } else if (v
->crashed_ctr
>= 2220 && !(v
->tick_counter
& 0x1F)) {
507 bool ret
= v
->Next() != NULL
;
508 DeleteLastRoadVeh(v
);
516 * Check routine whether a road and a train vehicle have collided.
517 * @param v %Train vehicle to test.
518 * @param data Road vehicle to test.
519 * @return %Train vehicle if the vehicles collided, else \c NULL.
521 static Vehicle
*EnumCheckRoadVehCrashTrain(Vehicle
*v
, void *data
)
523 const Vehicle
*u
= (Vehicle
*)data
;
525 return (v
->type
== VEH_TRAIN
&&
526 abs(v
->z_pos
- u
->z_pos
) <= 6 &&
527 abs(v
->x_pos
- u
->x_pos
) <= 4 &&
528 abs(v
->y_pos
- u
->y_pos
) <= 4) ? v
: NULL
;
531 uint
RoadVehicle::Crash(bool flooded
)
533 uint pass
= this->GroundVehicleBase::Crash(flooded
);
534 if (this->IsFrontEngine()) {
537 /* If we're in a drive through road stop we ought to leave it */
538 if (IsInsideMM(this->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
)) {
539 RoadStop::GetByTile(this->tile
, GetRoadStopType(this->tile
))->Leave(this);
542 this->crashed_ctr
= flooded
? 2000 : 1; // max 2220, disappear pretty fast when flooded
546 static void RoadVehCrash(RoadVehicle
*v
)
548 uint pass
= v
->Crash();
550 AI::NewEvent(v
->owner
, new ScriptEventVehicleCrashed(v
->index
, v
->tile
, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING
));
551 Game::NewEvent(new ScriptEventVehicleCrashed(v
->index
, v
->tile
, ScriptEventVehicleCrashed::CRASH_RV_LEVEL_CROSSING
));
556 STR_NEWS_ROAD_VEHICLE_CRASH_DRIVER
: STR_NEWS_ROAD_VEHICLE_CRASH
,
561 ModifyStationRatingAround(v
->tile
, v
->owner
, -160, 22);
562 if (_settings_client
.sound
.disaster
) SndPlayVehicleFx(SND_12_EXPLOSION
, v
);
565 static bool RoadVehCheckTrainCrash(RoadVehicle
*v
)
567 for (RoadVehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
568 if (u
->state
== RVSB_WORMHOLE
) continue;
570 TileIndex tile
= u
->tile
;
572 if (!IsLevelCrossingTile(tile
)) continue;
574 if (HasVehicleOnPosXY(v
->x_pos
, v
->y_pos
, u
, EnumCheckRoadVehCrashTrain
)) {
583 TileIndex
RoadVehicle::GetOrderStationLocation(StationID station
)
585 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
587 const Station
*st
= Station::Get(station
);
588 if (!CanVehicleUseStation(this, st
)) {
589 /* There is no stop left at the station, so don't even TRY to go there */
590 this->IncrementRealOrderIndex();
597 static void StartRoadVehSound(const RoadVehicle
*v
)
599 if (!PlayVehicleSound(v
, VSE_START
)) {
600 SoundID s
= RoadVehInfo(v
->engine_type
)->sfx
;
601 if (s
== SND_19_BUS_START_PULL_AWAY
&& (v
->tick_counter
& 3) == 0) {
602 s
= SND_1A_BUS_START_PULL_AWAY_WITH_HORN
;
604 SndPlayVehicleFx(s
, v
);
608 struct RoadVehFindData
{
617 static Vehicle
*EnumCheckRoadVehClose(Vehicle
*v
, void *data
)
619 static const int8 dist_x
[] = { -4, -8, -4, -1, 4, 8, 4, 1 };
620 static const int8 dist_y
[] = { -4, -1, 4, 8, 4, 1, -4, -8 };
622 RoadVehFindData
*rvf
= (RoadVehFindData
*)data
;
624 short x_diff
= v
->x_pos
- rvf
->x
;
625 short y_diff
= v
->y_pos
- rvf
->y
;
627 if (v
->type
== VEH_ROAD
&&
629 abs(v
->z_pos
- rvf
->veh
->z_pos
) < 6 &&
630 v
->direction
== rvf
->dir
&&
631 rvf
->veh
->First() != v
->First() &&
632 (dist_x
[v
->direction
] >= 0 || (x_diff
> dist_x
[v
->direction
] && x_diff
<= 0)) &&
633 (dist_x
[v
->direction
] <= 0 || (x_diff
< dist_x
[v
->direction
] && x_diff
>= 0)) &&
634 (dist_y
[v
->direction
] >= 0 || (y_diff
> dist_y
[v
->direction
] && y_diff
<= 0)) &&
635 (dist_y
[v
->direction
] <= 0 || (y_diff
< dist_y
[v
->direction
] && y_diff
>= 0))) {
636 uint diff
= abs(x_diff
) + abs(y_diff
);
638 if (diff
< rvf
->best_diff
|| (diff
== rvf
->best_diff
&& v
->index
< rvf
->best
->index
)) {
640 rvf
->best_diff
= diff
;
647 static RoadVehicle
*RoadVehFindCloseTo(RoadVehicle
*v
, int x
, int y
, Direction dir
, bool update_blocked_ctr
= true)
650 RoadVehicle
*front
= v
->First();
652 if (front
->reverse_ctr
!= 0) return NULL
;
658 rvf
.best_diff
= UINT_MAX
;
660 if (front
->state
== RVSB_WORMHOLE
) {
661 FindVehicleOnPos(v
->tile
, &rvf
, EnumCheckRoadVehClose
);
662 FindVehicleOnPos(GetOtherTunnelBridgeEnd(v
->tile
), &rvf
, EnumCheckRoadVehClose
);
664 FindVehicleOnPosXY(x
, y
, &rvf
, EnumCheckRoadVehClose
);
667 /* This code protects a roadvehicle from being blocked for ever
668 * If more than 1480 / 74 days a road vehicle is blocked, it will
669 * drive just through it. The ultimate backup-code of TTD.
670 * It can be disabled. */
671 if (rvf
.best_diff
== UINT_MAX
) {
672 front
->blocked_ctr
= 0;
676 if (update_blocked_ctr
&& ++front
->blocked_ctr
> 1480) return NULL
;
678 return RoadVehicle::From(rvf
.best
);
682 * A road vehicle arrives at a station. If it is the first time, create a news item.
683 * @param v Road vehicle that arrived.
684 * @param st Station where the road vehicle arrived.
686 static void RoadVehArrivesAt(const RoadVehicle
*v
, Station
*st
)
689 /* Check if station was ever visited before */
690 if (!(st
->had_vehicle_of_type
& HVOT_BUS
)) {
691 st
->had_vehicle_of_type
|= HVOT_BUS
;
692 SetDParam(0, st
->index
);
694 v
->roadtype
== ROADTYPE_ROAD
? STR_NEWS_FIRST_BUS_ARRIVAL
: STR_NEWS_FIRST_PASSENGER_TRAM_ARRIVAL
,
695 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
699 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
700 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
703 /* Check if station was ever visited before */
704 if (!(st
->had_vehicle_of_type
& HVOT_TRUCK
)) {
705 st
->had_vehicle_of_type
|= HVOT_TRUCK
;
706 SetDParam(0, st
->index
);
708 v
->roadtype
== ROADTYPE_ROAD
? STR_NEWS_FIRST_TRUCK_ARRIVAL
: STR_NEWS_FIRST_CARGO_TRAM_ARRIVAL
,
709 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
713 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
714 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
720 * This function looks at the vehicle and updates its speed (cur_speed
721 * and subspeed) variables. Furthermore, it returns the distance that
722 * the vehicle can drive this tick. #Vehicle::GetAdvanceDistance() determines
723 * the distance to drive before moving a step on the map.
724 * @return distance to drive.
726 int RoadVehicle::UpdateSpeed()
728 switch (_settings_game
.vehicle
.roadveh_acceleration_model
) {
729 default: NOT_REACHED();
731 return this->DoUpdateSpeed(this->overtaking
!= 0 ? 512 : 256, 0, this->GetCurrentMaxSpeed());
734 return this->DoUpdateSpeed(this->GetAcceleration() + (this->overtaking
!= 0 ? 256 : 0), this->GetAccelerationStatus() == AS_BRAKE
? 0 : 4, this->GetCurrentMaxSpeed());
738 static Direction
RoadVehGetNewDirection(const RoadVehicle
*v
, int x
, int y
)
740 static const Direction _roadveh_new_dir
[] = {
741 DIR_N
, DIR_NW
, DIR_W
, INVALID_DIR
,
742 DIR_NE
, DIR_N
, DIR_SW
, INVALID_DIR
,
743 DIR_E
, DIR_SE
, DIR_S
746 x
= x
- v
->x_pos
+ 1;
747 y
= y
- v
->y_pos
+ 1;
749 if ((uint
)x
> 2 || (uint
)y
> 2) return v
->direction
;
750 return _roadveh_new_dir
[y
* 4 + x
];
753 static Direction
RoadVehGetSlidingDirection(const RoadVehicle
*v
, int x
, int y
)
755 Direction new_dir
= RoadVehGetNewDirection(v
, x
, y
);
756 Direction old_dir
= v
->direction
;
759 if (new_dir
== old_dir
) return old_dir
;
760 delta
= (DirDifference(new_dir
, old_dir
) > DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
761 return ChangeDir(old_dir
, delta
);
764 struct OvertakeData
{
765 const RoadVehicle
*u
;
766 const RoadVehicle
*v
;
771 static Vehicle
*EnumFindVehBlockingOvertake(Vehicle
*v
, void *data
)
773 const OvertakeData
*od
= (OvertakeData
*)data
;
775 return (v
->type
== VEH_ROAD
&& v
->First() == v
&& v
!= od
->u
&& v
!= od
->v
) ? v
: NULL
;
779 * Check if overtaking is possible on a piece of track
781 * @param od Information about the tile and the involved vehicles
782 * @return true if we have to abort overtaking
784 static bool CheckRoadBlockedForOvertaking(OvertakeData
*od
)
786 TrackStatus ts
= GetTileTrackStatus(od
->tile
, TRANSPORT_ROAD
, od
->v
->compatible_roadtypes
);
787 TrackdirBits trackdirbits
= TrackStatusToTrackdirBits(ts
);
788 TrackdirBits red_signals
= TrackStatusToRedSignals(ts
); // barred level crossing
789 TrackBits trackbits
= TrackdirBitsToTrackBits(trackdirbits
);
791 /* Track does not continue along overtaking direction || track has junction || levelcrossing is barred */
792 if (!HasBit(trackdirbits
, od
->trackdir
) || (trackbits
& ~TRACK_BIT_CROSS
) || (red_signals
!= TRACKDIR_BIT_NONE
)) return true;
794 /* Are there more vehicles on the tile except the two vehicles involved in overtaking */
795 return HasVehicleOnPos(od
->tile
, od
, EnumFindVehBlockingOvertake
);
798 static void RoadVehCheckOvertake(RoadVehicle
*v
, RoadVehicle
*u
)
805 /* Trams can't overtake other trams */
806 if (v
->roadtype
== ROADTYPE_TRAM
) return;
808 /* Don't overtake in stations */
809 if (IsTileType(v
->tile
, MP_STATION
) || IsTileType(u
->tile
, MP_STATION
)) return;
811 /* For now, articulated road vehicles can't overtake anything. */
812 if (v
->HasArticulatedPart()) return;
814 /* Vehicles are not driving in same direction || direction is not a diagonal direction */
815 if (v
->direction
!= u
->direction
|| !(v
->direction
& 1)) return;
817 /* Check if vehicle is in a road stop, depot, tunnel or bridge or not on a straight road */
818 if (v
->state
>= RVSB_IN_ROAD_STOP
|| !IsStraightRoadTrackdir((Trackdir
)(v
->state
& RVSB_TRACKDIR_MASK
))) return;
820 /* Can't overtake a vehicle that is moving faster than us. If the vehicle in front is
821 * accelerating, take the maximum speed for the comparison, else the current speed.
822 * Original acceleration always accelerates, so always use the maximum speed. */
823 int u_speed
= (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
|| u
->GetAcceleration() > 0) ? u
->GetCurrentMaxSpeed() : u
->cur_speed
;
824 if (u_speed
>= v
->GetCurrentMaxSpeed() &&
825 !(u
->vehstatus
& VS_STOPPED
) &&
830 od
.trackdir
= DiagDirToDiagTrackdir(DirToDiagDir(v
->direction
));
832 /* Are the current and the next tile suitable for overtaking?
833 * - Does the track continue along od.trackdir
835 * - No barred levelcrossing
836 * - No other vehicles in the way
839 if (CheckRoadBlockedForOvertaking(&od
)) return;
841 od
.tile
= v
->tile
+ TileOffsByDiagDir(DirToDiagDir(v
->direction
));
842 if (CheckRoadBlockedForOvertaking(&od
)) return;
844 /* When the vehicle in front of us is stopped we may only take
845 * half the time to pass it than when the vehicle is moving. */
846 v
->overtaking_ctr
= (od
.u
->cur_speed
== 0 || (od
.u
->vehstatus
& VS_STOPPED
)) ? RV_OVERTAKE_TIMEOUT
/ 2 : 0;
847 v
->overtaking
= RVSB_DRIVE_SIDE
;
850 static void RoadZPosAffectSpeed(RoadVehicle
*v
, int old_z
)
852 if (old_z
== v
->z_pos
|| _settings_game
.vehicle
.roadveh_acceleration_model
!= AM_ORIGINAL
) return;
854 if (old_z
< v
->z_pos
) {
855 v
->cur_speed
= v
->cur_speed
* 232 / 256; // slow down by ~10%
857 uint16 spd
= v
->cur_speed
+ 2;
858 if (spd
<= v
->vcache
.cached_max_speed
) v
->cur_speed
= spd
;
862 static int PickRandomBit(uint bits
)
865 uint num
= RandomRange(CountBits(bits
));
867 for (i
= 0; !(bits
& 1) || (int)--num
>= 0; bits
>>= 1, i
++) {}
872 * Returns direction to for a road vehicle to take or
873 * INVALID_TRACKDIR if the direction is currently blocked
874 * @param v the Vehicle to do the pathfinding for
875 * @param tile the where to start the pathfinding
876 * @param enterdir the direction the vehicle enters the tile from
877 * @return the Trackdir to take
879 static Trackdir
RoadFindPathToDest(RoadVehicle
*v
, TileIndex tile
, DiagDirection enterdir
)
881 #define return_track(x) { best_track = (Trackdir)x; goto found_best_track; }
885 bool path_found
= true;
887 TrackStatus ts
= GetTileTrackStatus(tile
, TRANSPORT_ROAD
, v
->compatible_roadtypes
);
888 TrackdirBits red_signals
= TrackStatusToRedSignals(ts
); // crossing
889 TrackdirBits trackdirs
= TrackStatusToTrackdirBits(ts
);
891 if (IsTileType(tile
, MP_ROAD
)) {
892 if (IsRoadDepot(tile
) && (!IsTileOwner(tile
, v
->owner
) || GetRoadDepotDirection(tile
) == enterdir
|| (GetRoadTypes(tile
) & v
->compatible_roadtypes
) == 0)) {
893 /* Road depot owned by another company or with the wrong orientation */
894 trackdirs
= TRACKDIR_BIT_NONE
;
896 } else if (IsTileType(tile
, MP_STATION
) && IsStandardRoadStopTile(tile
)) {
897 /* Standard road stop (drive-through stops are treated as normal road) */
899 if (!IsTileOwner(tile
, v
->owner
) || GetRoadStopDir(tile
) == enterdir
|| v
->HasArticulatedPart()) {
900 /* different station owner or wrong orientation or the vehicle has articulated parts */
901 trackdirs
= TRACKDIR_BIT_NONE
;
904 RoadStopType rstype
= v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
;
906 if (GetRoadStopType(tile
) != rstype
) {
907 /* Wrong station type */
908 trackdirs
= TRACKDIR_BIT_NONE
;
910 /* Proper station type, check if there is free loading bay */
911 if (!_settings_game
.pf
.roadveh_queue
&& IsStandardRoadStopTile(tile
) &&
912 !RoadStop::GetByTile(tile
, rstype
)->HasFreeBay()) {
913 /* Station is full and RV queuing is off */
914 trackdirs
= TRACKDIR_BIT_NONE
;
919 /* The above lookups should be moved to GetTileTrackStatus in the
920 * future, but that requires more changes to the pathfinder and other
921 * stuff, probably even more arguments to GTTS.
924 /* Remove tracks unreachable from the enter dir */
925 trackdirs
&= DiagdirReachesTrackdirs(enterdir
);
926 if (trackdirs
== TRACKDIR_BIT_NONE
) {
927 /* No reachable tracks, so we'll reverse */
928 return_track(_road_reverse_table
[enterdir
]);
931 if (v
->reverse_ctr
!= 0) {
933 if (v
->roadtype
== ROADTYPE_TRAM
) {
934 /* Trams may only reverse on a tile if it contains at least the straight
935 * trackbits or when it is a valid turning tile (i.e. one roadbit) */
936 RoadBits rb
= GetAnyRoadBits(tile
, ROADTYPE_TRAM
);
937 RoadBits straight
= AxisToRoadBits(DiagDirToAxis(enterdir
));
938 reverse
= ((rb
& straight
) == straight
) ||
939 (rb
== DiagDirToRoadBits(enterdir
));
943 if (v
->tile
!= tile
) {
944 return_track(_road_reverse_table
[enterdir
]);
949 desttile
= v
->dest_tile
;
951 /* We've got no destination, pick a random track */
952 return_track(PickRandomBit(trackdirs
));
955 /* Only one track to choose between? */
956 if (KillFirstBit(trackdirs
) == TRACKDIR_BIT_NONE
) {
957 return_track(FindFirstBit2x64(trackdirs
));
960 switch (_settings_game
.pf
.pathfinder_for_roadvehs
) {
961 case VPF_NPF
: best_track
= NPFRoadVehicleChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
962 case VPF_YAPF
: best_track
= YapfRoadVehicleChooseTrack(v
, tile
, enterdir
, trackdirs
, path_found
); break;
964 default: NOT_REACHED();
966 v
->HandlePathfindingResult(path_found
);
970 if (HasBit(red_signals
, best_track
)) return INVALID_TRACKDIR
;
975 struct RoadDriveEntry
{
979 #include "table/roadveh_movement.h"
981 static bool RoadVehLeaveDepot(RoadVehicle
*v
, bool first
)
983 /* Don't leave unless v and following wagons are in the depot. */
984 for (const RoadVehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
985 if (u
->state
!= RVSB_IN_DEPOT
|| u
->tile
!= v
->tile
) return false;
988 DiagDirection dir
= GetRoadDepotDirection(v
->tile
);
989 v
->direction
= DiagDirToDir(dir
);
991 Trackdir tdir
= DiagDirToDiagTrackdir(dir
);
992 const RoadDriveEntry
*rdp
= _road_drive_data
[v
->roadtype
][(_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
) + tdir
];
994 int x
= TileX(v
->tile
) * TILE_SIZE
+ (rdp
[RVC_DEPOT_START_FRAME
].x
& 0xF);
995 int y
= TileY(v
->tile
) * TILE_SIZE
+ (rdp
[RVC_DEPOT_START_FRAME
].y
& 0xF);
998 /* We are leaving a depot, but have to go to the exact same one; re-enter */
999 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) && v
->tile
== v
->dest_tile
) {
1000 VehicleEnterDepot(v
);
1004 if (RoadVehFindCloseTo(v
, x
, y
, v
->direction
, false) != NULL
) return true;
1006 VehicleServiceInDepot(v
);
1008 StartRoadVehSound(v
);
1010 /* Vehicle is about to leave a depot */
1014 v
->vehstatus
&= ~VS_HIDDEN
;
1016 v
->frame
= RVC_DEPOT_START_FRAME
;
1020 v
->UpdatePosition();
1021 v
->UpdateInclination(true, true);
1023 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
1028 static Trackdir
FollowPreviousRoadVehicle(const RoadVehicle
*v
, const RoadVehicle
*prev
, TileIndex tile
, DiagDirection entry_dir
, bool already_reversed
)
1030 if (prev
->tile
== v
->tile
&& !already_reversed
) {
1031 /* If the previous vehicle is on the same tile as this vehicle is
1032 * then it must have reversed. */
1033 return _road_reverse_table
[entry_dir
];
1036 byte prev_state
= prev
->state
;
1039 if (prev_state
== RVSB_WORMHOLE
|| prev_state
== RVSB_IN_DEPOT
) {
1040 DiagDirection diag_dir
= INVALID_DIAGDIR
;
1042 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1043 diag_dir
= GetTunnelBridgeDirection(tile
);
1044 } else if (IsRoadDepotTile(tile
)) {
1045 diag_dir
= ReverseDiagDir(GetRoadDepotDirection(tile
));
1048 if (diag_dir
== INVALID_DIAGDIR
) return INVALID_TRACKDIR
;
1049 dir
= DiagDirToDiagTrackdir(diag_dir
);
1051 if (already_reversed
&& prev
->tile
!= tile
) {
1053 * The vehicle has reversed, but did not go straight back.
1054 * It immediately turn onto another tile. This means that
1055 * the roadstate of the previous vehicle cannot be used
1056 * as the direction we have to go with this vehicle.
1058 * Next table is build in the following way:
1059 * - first row for when the vehicle in front went to the northern or
1060 * western tile, second for southern and eastern.
1061 * - columns represent the entry direction.
1062 * - cell values are determined by the Trackdir one has to take from
1063 * the entry dir (column) to the tile in north or south by only
1064 * going over the trackdirs used for turning 90 degrees, i.e.
1065 * TRACKDIR_{UPPER,RIGHT,LOWER,LEFT}_{N,E,S,W}.
1067 static const Trackdir reversed_turn_lookup
[2][DIAGDIR_END
] = {
1068 { TRACKDIR_UPPER_W
, TRACKDIR_RIGHT_N
, TRACKDIR_LEFT_N
, TRACKDIR_UPPER_E
},
1069 { TRACKDIR_RIGHT_S
, TRACKDIR_LOWER_W
, TRACKDIR_LOWER_E
, TRACKDIR_LEFT_S
}};
1070 dir
= reversed_turn_lookup
[prev
->tile
< tile
? 0 : 1][ReverseDiagDir(entry_dir
)];
1071 } else if (HasBit(prev_state
, RVS_IN_DT_ROAD_STOP
)) {
1072 dir
= (Trackdir
)(prev_state
& RVSB_ROAD_STOP_TRACKDIR_MASK
);
1073 } else if (prev_state
< TRACKDIR_END
) {
1074 dir
= (Trackdir
)prev_state
;
1076 return INVALID_TRACKDIR
;
1080 /* Do some sanity checking. */
1081 static const RoadBits required_roadbits
[] = {
1082 ROAD_X
, ROAD_Y
, ROAD_NW
| ROAD_NE
, ROAD_SW
| ROAD_SE
,
1083 ROAD_NW
| ROAD_SW
, ROAD_NE
| ROAD_SE
, ROAD_X
, ROAD_Y
1085 RoadBits required
= required_roadbits
[dir
& 0x07];
1087 if ((required
& GetAnyRoadBits(tile
, v
->roadtype
, true)) == ROAD_NONE
) {
1088 dir
= INVALID_TRACKDIR
;
1095 * Can a tram track build without destruction on the given tile?
1096 * @param c the company that would be building the tram tracks
1097 * @param t the tile to build on.
1098 * @param r the road bits needed.
1099 * @return true when a track track can be build on 't'
1101 static bool CanBuildTramTrackOnTile(CompanyID c
, TileIndex t
, RoadBits r
)
1103 /* The 'current' company is not necessarily the owner of the vehicle. */
1104 Backup
<CompanyByte
> cur_company(_current_company
, c
, FILE_LINE
);
1106 CommandCost ret
= DoCommand(t
, ROADTYPE_TRAM
<< 4 | r
, 0, DC_NO_WATER
, CMD_BUILD_ROAD
);
1108 cur_company
.Restore();
1109 return ret
.Succeeded();
1112 bool IndividualRoadVehicleController(RoadVehicle
*v
, const RoadVehicle
*prev
)
1114 if (v
->overtaking
!= 0) {
1115 if (IsTileType(v
->tile
, MP_STATION
)) {
1116 /* Force us to be not overtaking! */
1118 } else if (++v
->overtaking_ctr
>= RV_OVERTAKE_TIMEOUT
) {
1119 /* If overtaking just aborts at a random moment, we can have a out-of-bound problem,
1120 * if the vehicle started a corner. To protect that, only allow an abort of
1121 * overtake if we are on straight roads */
1122 if (v
->state
< RVSB_IN_ROAD_STOP
&& IsStraightRoadTrackdir((Trackdir
)v
->state
)) {
1128 /* If this vehicle is in a depot and we've reached this point it must be
1129 * one of the articulated parts. It will stay in the depot until activated
1130 * by the previous vehicle in the chain when it gets to the right place. */
1131 if (v
->IsInDepot()) return true;
1133 if (v
->state
== RVSB_WORMHOLE
) {
1134 /* Vehicle is entering a depot or is on a bridge or in a tunnel */
1135 GetNewVehiclePosResult gp
= GetNewVehiclePos(v
);
1137 if (v
->IsFrontEngine()) {
1138 const Vehicle
*u
= RoadVehFindCloseTo(v
, gp
.x
, gp
.y
, v
->direction
);
1140 v
->cur_speed
= u
->First()->cur_speed
;
1145 if (IsTileType(gp
.new_tile
, MP_TUNNELBRIDGE
) && HasBit(VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
), VETS_ENTERED_WORMHOLE
)) {
1146 /* Vehicle has just entered a bridge or tunnel */
1149 v
->UpdatePosition();
1150 v
->UpdateInclination(true, true);
1156 v
->UpdatePosition();
1157 if ((v
->vehstatus
& VS_HIDDEN
) == 0) v
->Vehicle::UpdateViewport(true);
1161 /* Get move position data for next frame.
1162 * For a drive-through road stop use 'straight road' move data.
1163 * In this case v->state is masked to give the road stop entry direction. */
1164 RoadDriveEntry rd
= _road_drive_data
[v
->roadtype
][(
1165 (HasBit(v
->state
, RVS_IN_DT_ROAD_STOP
) ? v
->state
& RVSB_ROAD_STOP_TRACKDIR_MASK
: v
->state
) +
1166 (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)) ^ v
->overtaking
][v
->frame
+ 1];
1168 if (rd
.x
& RDE_NEXT_TILE
) {
1169 TileIndex tile
= v
->tile
+ TileOffsByDiagDir((DiagDirection
)(rd
.x
& 3));
1172 if (v
->IsFrontEngine()) {
1173 /* If this is the front engine, look for the right path. */
1174 dir
= RoadFindPathToDest(v
, tile
, (DiagDirection
)(rd
.x
& 3));
1176 dir
= FollowPreviousRoadVehicle(v
, prev
, tile
, (DiagDirection
)(rd
.x
& 3), false);
1179 if (dir
== INVALID_TRACKDIR
) {
1180 if (!v
->IsFrontEngine()) error("Disconnecting road vehicle.");
1186 uint start_frame
= RVC_DEFAULT_START_FRAME
;
1187 if (IsReversingRoadTrackdir(dir
)) {
1188 /* When turning around we can't be overtaking. */
1191 /* Turning around */
1192 if (v
->roadtype
== ROADTYPE_TRAM
) {
1193 /* Determine the road bits the tram needs to be able to turn around
1194 * using the 'big' corner loop. */
1197 default: NOT_REACHED();
1198 case TRACKDIR_RVREV_NE
: needed
= ROAD_SW
; break;
1199 case TRACKDIR_RVREV_SE
: needed
= ROAD_NW
; break;
1200 case TRACKDIR_RVREV_SW
: needed
= ROAD_NE
; break;
1201 case TRACKDIR_RVREV_NW
: needed
= ROAD_SE
; break;
1203 if ((v
->Previous() != NULL
&& v
->Previous()->tile
== tile
) ||
1204 (v
->IsFrontEngine() && IsNormalRoadTile(tile
) && !HasRoadWorks(tile
) &&
1205 (needed
& GetRoadBits(tile
, ROADTYPE_TRAM
)) != ROAD_NONE
)) {
1207 * Taking the 'big' corner for trams only happens when:
1208 * - The previous vehicle in this (articulated) tram chain is
1209 * already on the 'next' tile, we just follow them regardless of
1210 * anything. When it is NOT on the 'next' tile, the tram started
1211 * doing a reversing turn when the piece of tram track on the next
1212 * tile did not exist yet. Do not use the big tram loop as that is
1213 * going to cause the tram to split up.
1214 * - Or the front of the tram can drive over the next tile.
1216 } else if (!v
->IsFrontEngine() || !CanBuildTramTrackOnTile(v
->owner
, tile
, needed
) || ((~needed
& GetAnyRoadBits(v
->tile
, ROADTYPE_TRAM
, false)) == ROAD_NONE
)) {
1218 * Taking the 'small' corner for trams only happens when:
1219 * - We are not the from vehicle of an articulated tram.
1220 * - Or when the company cannot build on the next tile.
1222 * The 'small' corner means that the vehicle is on the end of a
1223 * tram track and needs to start turning there. To do this properly
1224 * the tram needs to start at an offset in the tram turning 'code'
1225 * for 'big' corners. It furthermore does not go to the next tile,
1226 * so that needs to be fixed too.
1229 start_frame
= RVC_TURN_AROUND_START_FRAME_SHORT_TRAM
;
1231 /* The company can build on the next tile, so wait till (s)he does. */
1235 } else if (IsNormalRoadTile(v
->tile
) && GetDisallowedRoadDirections(v
->tile
) != DRD_NONE
) {
1243 /* Get position data for first frame on the new tile */
1244 const RoadDriveEntry
*rdp
= _road_drive_data
[v
->roadtype
][(dir
+ (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)) ^ v
->overtaking
];
1246 int x
= TileX(tile
) * TILE_SIZE
+ rdp
[start_frame
].x
;
1247 int y
= TileY(tile
) * TILE_SIZE
+ rdp
[start_frame
].y
;
1249 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1250 if (v
->IsFrontEngine()) {
1251 Vehicle
*u
= RoadVehFindCloseTo(v
, x
, y
, new_dir
);
1253 v
->cur_speed
= u
->First()->cur_speed
;
1258 uint32 r
= VehicleEnterTile(v
, tile
, x
, y
);
1259 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1260 if (!IsTileType(tile
, MP_TUNNELBRIDGE
)) {
1264 /* Try an about turn to re-enter the previous tile */
1265 dir
= _road_reverse_table
[rd
.x
& 3];
1269 if (IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) && IsTileType(v
->tile
, MP_STATION
)) {
1270 if (IsReversingRoadTrackdir(dir
) && IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) {
1271 /* New direction is trying to turn vehicle around.
1272 * We can't turn at the exit of a road stop so wait.*/
1277 /* If we are a drive through road stop and the next tile is of
1278 * the same road stop and the next tile isn't this one (i.e. we
1279 * are not reversing), then keep the reservation and state.
1280 * This way we will not be shortly unregister from the road
1281 * stop. It also makes it possible to load when on the edge of
1282 * two road stops; otherwise you could get vehicles that should
1283 * be loading but are not actually loading. */
1284 if (IsDriveThroughStopTile(v
->tile
) &&
1285 RoadStop::IsDriveThroughRoadStopContinuation(v
->tile
, tile
) &&
1287 /* So, keep 'our' state */
1288 dir
= (Trackdir
)v
->state
;
1289 } else if (IsRoadStop(v
->tile
)) {
1290 /* We're not continuing our drive through road stop, so leave. */
1291 RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
))->Leave(v
);
1295 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) {
1297 v
->state
= (byte
)dir
;
1298 v
->frame
= start_frame
;
1300 if (new_dir
!= v
->direction
) {
1301 v
->direction
= new_dir
;
1302 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1306 v
->UpdatePosition();
1307 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, true));
1311 if (rd
.x
& RDE_TURNED
) {
1312 /* Vehicle has finished turning around, it will now head back onto the same tile */
1314 uint turn_around_start_frame
= RVC_TURN_AROUND_START_FRAME
;
1316 if (v
->roadtype
== ROADTYPE_TRAM
&& !IsRoadDepotTile(v
->tile
) && HasExactlyOneBit(GetAnyRoadBits(v
->tile
, ROADTYPE_TRAM
, true))) {
1318 * The tram is turning around with one tram 'roadbit'. This means that
1319 * it is using the 'big' corner 'drive data'. However, to support the
1320 * trams to take a small corner, there is a 'turned' marker in the middle
1321 * of the turning 'drive data'. When the tram took the long corner, we
1322 * will still use the 'big' corner drive data, but we advance it one
1323 * frame. We furthermore set the driving direction so the turning is
1324 * going to be properly shown.
1326 turn_around_start_frame
= RVC_START_FRAME_AFTER_LONG_TRAM
;
1327 switch (rd
.x
& 0x3) {
1328 default: NOT_REACHED();
1329 case DIAGDIR_NW
: dir
= TRACKDIR_RVREV_SE
; break;
1330 case DIAGDIR_NE
: dir
= TRACKDIR_RVREV_SW
; break;
1331 case DIAGDIR_SE
: dir
= TRACKDIR_RVREV_NW
; break;
1332 case DIAGDIR_SW
: dir
= TRACKDIR_RVREV_NE
; break;
1335 if (v
->IsFrontEngine()) {
1336 /* If this is the front engine, look for the right path. */
1337 dir
= RoadFindPathToDest(v
, v
->tile
, (DiagDirection
)(rd
.x
& 3));
1339 dir
= FollowPreviousRoadVehicle(v
, prev
, v
->tile
, (DiagDirection
)(rd
.x
& 3), true);
1343 if (dir
== INVALID_TRACKDIR
) {
1348 const RoadDriveEntry
*rdp
= _road_drive_data
[v
->roadtype
][(_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
) + dir
];
1350 int x
= TileX(v
->tile
) * TILE_SIZE
+ rdp
[turn_around_start_frame
].x
;
1351 int y
= TileY(v
->tile
) * TILE_SIZE
+ rdp
[turn_around_start_frame
].y
;
1353 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1354 if (v
->IsFrontEngine() && RoadVehFindCloseTo(v
, x
, y
, new_dir
) != NULL
) return false;
1356 uint32 r
= VehicleEnterTile(v
, v
->tile
, x
, y
);
1357 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1363 v
->frame
= turn_around_start_frame
;
1365 if (new_dir
!= v
->direction
) {
1366 v
->direction
= new_dir
;
1367 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1372 v
->UpdatePosition();
1373 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, true));
1377 /* This vehicle is not in a wormhole and it hasn't entered a new tile. If
1378 * it's on a depot tile, check if it's time to activate the next vehicle in
1380 if (v
->Next() != NULL
&& IsRoadDepotTile(v
->tile
)) {
1381 if (v
->frame
== v
->gcache
.cached_veh_length
+ RVC_DEPOT_START_FRAME
) {
1382 RoadVehLeaveDepot(v
->Next(), false);
1386 /* Calculate new position for the vehicle */
1387 int x
= (v
->x_pos
& ~15) + (rd
.x
& 15);
1388 int y
= (v
->y_pos
& ~15) + (rd
.y
& 15);
1390 Direction new_dir
= RoadVehGetSlidingDirection(v
, x
, y
);
1392 if (v
->IsFrontEngine() && !IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
)) {
1393 /* Vehicle is not in a road stop.
1394 * Check for another vehicle to overtake */
1395 RoadVehicle
*u
= RoadVehFindCloseTo(v
, x
, y
, new_dir
);
1399 /* There is a vehicle in front overtake it if possible */
1400 if (v
->overtaking
== 0) RoadVehCheckOvertake(v
, u
);
1401 if (v
->overtaking
== 0) v
->cur_speed
= u
->cur_speed
;
1403 /* In case an RV is stopped in a road stop, why not try to load? */
1404 if (v
->cur_speed
== 0 && IsInsideMM(v
->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) &&
1405 v
->current_order
.ShouldStopAtStation(v
, GetStationIndex(v
->tile
)) &&
1406 v
->owner
== GetTileOwner(v
->tile
) && !v
->current_order
.IsType(OT_LEAVESTATION
) &&
1407 GetRoadStopType(v
->tile
) == (v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
)) {
1408 Station
*st
= Station::GetByTile(v
->tile
);
1409 v
->last_station_visited
= st
->index
;
1410 RoadVehArrivesAt(v
, st
);
1417 Direction old_dir
= v
->direction
;
1418 if (new_dir
!= old_dir
) {
1419 v
->direction
= new_dir
;
1420 if (_settings_game
.vehicle
.roadveh_acceleration_model
== AM_ORIGINAL
) v
->cur_speed
-= v
->cur_speed
>> 2;
1422 /* Delay the vehicle in curves by making it require one additional frame per turning direction (two in total).
1423 * A vehicle has to spend at least 9 frames on a tile, so the following articulated part can follow.
1424 * (The following part may only be one tile behind, and the front part is moved before the following ones.)
1425 * The short (inner) curve has 8 frames, this elongates it to 10. */
1426 v
->UpdateInclination(false, true);
1430 /* If the vehicle is in a normal road stop and the frame equals the stop frame OR
1431 * if the vehicle is in a drive-through road stop and this is the destination station
1432 * and it's the correct type of stop (bus or truck) and the frame equals the stop frame...
1433 * (the station test and stop type test ensure that other vehicles, using the road stop as
1434 * a through route, do not stop) */
1435 if (v
->IsFrontEngine() && ((IsInsideMM(v
->state
, RVSB_IN_ROAD_STOP
, RVSB_IN_ROAD_STOP_END
) &&
1436 _road_stop_stop_frame
[v
->state
- RVSB_IN_ROAD_STOP
+ (_settings_game
.vehicle
.road_side
<< RVS_DRIVE_SIDE
)] == v
->frame
) ||
1437 (IsInsideMM(v
->state
, RVSB_IN_DT_ROAD_STOP
, RVSB_IN_DT_ROAD_STOP_END
) &&
1438 v
->current_order
.ShouldStopAtStation(v
, GetStationIndex(v
->tile
)) &&
1439 v
->owner
== GetTileOwner(v
->tile
) &&
1440 GetRoadStopType(v
->tile
) == (v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
) &&
1441 v
->frame
== RVC_DRIVE_THROUGH_STOP_FRAME
))) {
1443 RoadStop
*rs
= RoadStop::GetByTile(v
->tile
, GetRoadStopType(v
->tile
));
1444 Station
*st
= Station::GetByTile(v
->tile
);
1446 /* Vehicle is at the stop position (at a bay) in a road stop.
1447 * Note, if vehicle is loading/unloading it has already been handled,
1448 * so if we get here the vehicle has just arrived or is just ready to leave. */
1449 if (!HasBit(v
->state
, RVS_ENTERED_STOP
)) {
1450 /* Vehicle has arrived at a bay in a road stop */
1452 if (IsDriveThroughStopTile(v
->tile
)) {
1453 TileIndex next_tile
= TileAddByDir(v
->tile
, v
->direction
);
1455 /* Check if next inline bay is free and has compatible road. */
1456 if (RoadStop::IsDriveThroughRoadStopContinuation(v
->tile
, next_tile
) && (GetRoadTypes(next_tile
) & v
->compatible_roadtypes
) != 0) {
1460 v
->UpdatePosition();
1461 RoadZPosAffectSpeed(v
, v
->UpdateInclination(true, false));
1466 rs
->SetEntranceBusy(false);
1467 SetBit(v
->state
, RVS_ENTERED_STOP
);
1469 v
->last_station_visited
= st
->index
;
1471 if (IsDriveThroughStopTile(v
->tile
) || (v
->current_order
.IsType(OT_GOTO_STATION
) && v
->current_order
.GetDestination() == st
->index
)) {
1472 RoadVehArrivesAt(v
, st
);
1477 /* Vehicle is ready to leave a bay in a road stop */
1478 if (rs
->IsEntranceBusy()) {
1479 /* Road stop entrance is busy, so wait as there is nowhere else to go */
1483 if (v
->current_order
.IsType(OT_LEAVESTATION
)) v
->current_order
.Free();
1486 if (IsStandardRoadStopTile(v
->tile
)) rs
->SetEntranceBusy(true);
1488 StartRoadVehSound(v
);
1489 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1492 /* Check tile position conditions - i.e. stop position in depot,
1493 * entry onto bridge or into tunnel */
1494 uint32 r
= VehicleEnterTile(v
, v
->tile
, x
, y
);
1495 if (HasBit(r
, VETS_CANNOT_ENTER
)) {
1500 if (v
->current_order
.IsType(OT_LEAVESTATION
) && IsDriveThroughStopTile(v
->tile
)) {
1501 v
->current_order
.Free();
1504 /* Move to next frame unless vehicle arrived at a stop position
1505 * in a depot or entered a tunnel/bridge */
1506 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) v
->frame
++;
1509 v
->UpdatePosition();
1510 RoadZPosAffectSpeed(v
, v
->UpdateInclination(false, true));
1514 static bool RoadVehController(RoadVehicle
*v
)
1516 /* decrease counters */
1517 v
->current_order_time
++;
1518 if (v
->reverse_ctr
!= 0) v
->reverse_ctr
--;
1520 /* handle crashed */
1521 if (v
->vehstatus
& VS_CRASHED
|| RoadVehCheckTrainCrash(v
)) {
1522 return RoadVehIsCrashed(v
);
1525 /* road vehicle has broken down? */
1526 if (v
->HandleBreakdown()) return true;
1527 if (v
->vehstatus
& VS_STOPPED
) return true;
1532 if (v
->current_order
.IsType(OT_LOADING
)) return true;
1534 if (v
->IsInDepot() && RoadVehLeaveDepot(v
, true)) return true;
1536 v
->ShowVisualEffect();
1538 /* Check how far the vehicle needs to proceed */
1539 int j
= v
->UpdateSpeed();
1541 int adv_spd
= v
->GetAdvanceDistance();
1542 bool blocked
= false;
1543 while (j
>= adv_spd
) {
1547 for (RoadVehicle
*prev
= NULL
; u
!= NULL
; prev
= u
, u
= u
->Next()) {
1548 if (!IndividualRoadVehicleController(u
, prev
)) {
1555 /* Determine distance to next map position */
1556 adv_spd
= v
->GetAdvanceDistance();
1558 /* Test for a collision, but only if another movement will occur. */
1559 if (j
>= adv_spd
&& RoadVehCheckTrainCrash(v
)) break;
1564 for (RoadVehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1565 if ((u
->vehstatus
& VS_HIDDEN
) != 0) continue;
1567 u
->UpdateViewport(false, false);
1570 /* If movement is blocked, set 'progress' to its maximum, so the roadvehicle does
1571 * not accelerate again before it can actually move. I.e. make sure it tries to advance again
1572 * on next tick to discover whether it is still blocked. */
1573 if (v
->progress
== 0) v
->progress
= blocked
? adv_spd
- 1 : j
;
1578 Money
RoadVehicle::GetRunningCost() const
1580 const Engine
*e
= this->GetEngine();
1581 if (e
->u
.road
.running_cost_class
== INVALID_PRICE
) return 0;
1583 uint cost_factor
= GetVehicleProperty(this, PROP_ROADVEH_RUNNING_COST_FACTOR
, e
->u
.road
.running_cost
);
1584 if (cost_factor
== 0) return 0;
1586 return GetPrice(e
->u
.road
.running_cost_class
, cost_factor
, e
->GetGRF());
1589 bool RoadVehicle::Tick()
1591 PerformanceAccumulator
framerate(PFE_GL_ROADVEHS
);
1593 this->tick_counter
++;
1595 if (this->IsFrontEngine()) {
1596 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
1597 return RoadVehController(this);
1603 static void CheckIfRoadVehNeedsService(RoadVehicle
*v
)
1605 /* If we already got a slot at a stop, use that FIRST, and go to a depot later */
1606 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_roadveh
== 0 || !v
->NeedsAutomaticServicing()) return;
1607 if (v
->IsChainInDepot()) {
1608 VehicleServiceInDepot(v
);
1613 switch (_settings_game
.pf
.pathfinder_for_roadvehs
) {
1614 case VPF_NPF
: max_penalty
= _settings_game
.pf
.npf
.maximum_go_to_depot_penalty
; break;
1615 case VPF_YAPF
: max_penalty
= _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
; break;
1616 default: NOT_REACHED();
1619 FindDepotData rfdd
= FindClosestRoadDepot(v
, max_penalty
);
1620 /* Only go to the depot if it is not too far out of our way. */
1621 if (rfdd
.best_length
== UINT_MAX
|| rfdd
.best_length
> max_penalty
) {
1622 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
1623 /* If we were already heading for a depot but it has
1624 * suddenly moved farther away, we continue our normal
1626 v
->current_order
.MakeDummy();
1627 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1632 DepotID depot
= GetDepotIndex(rfdd
.tile
);
1634 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
1635 v
->current_order
.GetNonStopType() & ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
&&
1640 SetBit(v
->gv_flags
, GVF_SUPPRESS_IMPLICIT_ORDERS
);
1641 v
->current_order
.MakeGoToDepot(depot
, ODTFB_SERVICE
);
1642 v
->SetDestTile(rfdd
.tile
);
1643 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
1646 void RoadVehicle::OnNewDay()
1650 if (!this->IsFrontEngine()) return;
1652 if ((++this->day_counter
& 7) == 0) DecreaseVehicleValue(this);
1653 if (this->blocked_ctr
== 0) CheckVehicleBreakdown(this);
1655 CheckIfRoadVehNeedsService(this);
1659 if (this->running_ticks
== 0) return;
1661 CommandCost
cost(EXPENSES_ROADVEH_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
1663 this->profit_this_year
-= cost
.GetCost();
1664 this->running_ticks
= 0;
1666 SubtractMoneyFromCompanyFract(this->owner
, cost
);
1668 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
1669 SetWindowClassesDirty(WC_ROADVEH_LIST
);
1672 Trackdir
RoadVehicle::GetVehicleTrackdir() const
1674 if (this->vehstatus
& VS_CRASHED
) return INVALID_TRACKDIR
;
1676 if (this->IsInDepot()) {
1677 /* We'll assume the road vehicle is facing outwards */
1678 return DiagDirToDiagTrackdir(GetRoadDepotDirection(this->tile
));
1681 if (IsStandardRoadStopTile(this->tile
)) {
1682 /* We'll assume the road vehicle is facing outwards */
1683 return DiagDirToDiagTrackdir(GetRoadStopDir(this->tile
)); // Road vehicle in a station
1686 /* Drive through road stops / wormholes (tunnels) */
1687 if (this->state
> RVSB_TRACKDIR_MASK
) return DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
1689 /* If vehicle's state is a valid track direction (vehicle is not turning around) return it,
1690 * otherwise transform it into a valid track direction */
1691 return (Trackdir
)((IsReversingRoadTrackdir((Trackdir
)this->state
)) ? (this->state
- 6) : this->state
);