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 ship_cmd.cpp Handling of ships. */
14 #include "dock_base.h"
15 #include "landscape.h"
16 #include "timetable.h"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "pathfinder/npf/npf_func.h"
20 #include "depot_base.h"
21 #include "station_base.h"
22 #include "newgrf_engine.h"
23 #include "pathfinder/yapf/yapf.h"
24 #include "newgrf_sound.h"
25 #include "spritecache.h"
26 #include "strings_func.h"
27 #include "window_func.h"
28 #include "date_func.h"
29 #include "vehicle_func.h"
30 #include "sound_func.h"
32 #include "game/game.hpp"
33 #include "pathfinder/opf/opf_ship.h"
34 #include "engine_base.h"
35 #include "company_base.h"
36 #include "tunnelbridge_map.h"
37 #include "zoom_func.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
44 * Determine the effective #WaterClass for a ship travelling on a tile.
45 * @param tile Tile of interest
46 * @return the waterclass to be used by the ship.
48 WaterClass
GetEffectiveWaterClass(TileIndex tile
)
50 if (HasTileWaterClass(tile
)) return GetWaterClass(tile
);
51 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
52 assert(GetTunnelBridgeTransportType(tile
) == TRANSPORT_WATER
);
53 return WATER_CLASS_CANAL
;
55 if (IsTileType(tile
, MP_RAILWAY
)) {
56 assert(GetRailGroundType(tile
) == RAIL_GROUND_WATER
);
57 return WATER_CLASS_SEA
;
62 static const uint16 _ship_sprites
[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
65 bool IsValidImageIndex
<VEH_SHIP
>(uint8 image_index
)
67 return image_index
< lengthof(_ship_sprites
);
70 static inline TrackBits
GetTileShipTrackStatus(TileIndex tile
)
72 return TrackStatusToTrackBits(GetTileTrackStatus(tile
, TRANSPORT_WATER
, 0));
75 static void GetShipIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
77 const Engine
*e
= Engine::Get(engine
);
78 uint8 spritenum
= e
->u
.ship
.image_index
;
80 if (is_custom_sprite(spritenum
)) {
81 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
82 if (result
->IsValid()) return;
84 spritenum
= e
->original_image_index
;
87 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
88 result
->Set(DIR_W
+ _ship_sprites
[spritenum
]);
91 void DrawShipEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
94 GetShipIcon(engine
, image_type
, &seq
);
96 Rect16 rect
= seq
.GetBounds();
97 preferred_x
= Clamp(preferred_x
,
98 left
- UnScaleGUI(rect
.left
),
99 right
- UnScaleGUI(rect
.right
));
101 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
105 * Get the size of the sprite of a ship sprite heading west (used for lists).
106 * @param engine The engine to get the sprite from.
107 * @param[out] width The width of the sprite.
108 * @param[out] height The height of the sprite.
109 * @param[out] xoffs Number of pixels to shift the sprite to the right.
110 * @param[out] yoffs Number of pixels to shift the sprite downwards.
111 * @param image_type Context the sprite is used in.
113 void GetShipSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
115 VehicleSpriteSeq seq
;
116 GetShipIcon(engine
, image_type
, &seq
);
118 Rect16 rect
= seq
.GetBounds();
120 width
= UnScaleGUI(rect
.right
- rect
.left
+ 1);
121 height
= UnScaleGUI(rect
.bottom
- rect
.top
+ 1);
122 xoffs
= UnScaleGUI(rect
.left
);
123 yoffs
= UnScaleGUI(rect
.top
);
126 void Ship::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
128 uint8 spritenum
= this->spritenum
;
130 if (is_custom_sprite(spritenum
)) {
131 GetCustomVehicleSprite(this, direction
, image_type
, result
);
132 if (result
->IsValid()) return;
134 spritenum
= this->GetEngine()->original_image_index
;
137 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
138 result
->Set(_ship_sprites
[spritenum
] + direction
);
141 static const Depot
*FindClosestShipDepot(const Vehicle
*v
, uint max_distance
)
143 /* Find the closest depot */
145 const Depot
*best_depot
= nullptr;
146 /* If we don't have a maximum distance, i.e. distance = 0,
147 * we want to find any depot so the best distance of no
148 * depot must be more than any correct distance. On the
149 * other hand if we have set a maximum distance, any depot
150 * further away than max_distance can safely be ignored. */
151 uint best_dist
= max_distance
== 0 ? UINT_MAX
: max_distance
+ 1;
153 FOR_ALL_DEPOTS(depot
) {
154 TileIndex tile
= depot
->xy
;
155 if (IsShipDepotTile(tile
) && IsTileOwner(tile
, v
->owner
)) {
156 uint dist
= DistanceManhattan(tile
, v
->tile
);
157 if (dist
< best_dist
) {
167 static void CheckIfShipNeedsService(Vehicle
*v
)
169 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_ships
== 0 || !v
->NeedsAutomaticServicing()) return;
170 if (v
->IsChainInDepot()) {
171 VehicleServiceInDepot(v
);
176 switch (_settings_game
.pf
.pathfinder_for_ships
) {
177 case VPF_OPF
: max_distance
= 12; break;
178 case VPF_NPF
: max_distance
= _settings_game
.pf
.npf
.maximum_go_to_depot_penalty
/ NPF_TILE_LENGTH
; break;
179 case VPF_YAPF
: max_distance
= _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
/ YAPF_TILE_LENGTH
; break;
180 default: NOT_REACHED();
183 const Depot
*depot
= FindClosestShipDepot(v
, max_distance
);
185 if (depot
== nullptr) {
186 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
187 v
->current_order
.MakeDummy();
188 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
193 v
->current_order
.MakeGoToDepot(depot
->index
, ODTFB_SERVICE
);
194 v
->dest_tile
= depot
->xy
;
195 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
199 * Update the caches of this ship.
201 void Ship::UpdateCache()
203 const ShipVehicleInfo
*svi
= ShipVehInfo(this->engine_type
);
205 /* Get speed fraction for the current water type. Aqueducts are always canals. */
206 bool is_ocean
= GetEffectiveWaterClass(this->tile
) == WATER_CLASS_SEA
;
207 uint raw_speed
= GetVehicleProperty(this, PROP_SHIP_SPEED
, svi
->max_speed
);
208 this->vcache
.cached_max_speed
= svi
->ApplyWaterClassSpeedFrac(raw_speed
, is_ocean
);
210 /* Update cargo aging period. */
211 this->vcache
.cached_cargo_age_period
= GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD
, EngInfo(this->engine_type
)->cargo_age_period
);
213 this->UpdateVisualEffect();
216 Money
Ship::GetRunningCost() const
218 const Engine
*e
= this->GetEngine();
219 uint cost_factor
= GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR
, e
->u
.ship
.running_cost
);
220 return GetPrice(PR_RUNNING_SHIP
, cost_factor
, e
->GetGRF());
223 void Ship::OnNewDay()
225 if ((++this->day_counter
& 7) == 0) {
226 DecreaseVehicleValue(this);
229 CheckVehicleBreakdown(this);
231 CheckIfShipNeedsService(this);
235 if (this->running_ticks
== 0) return;
237 CommandCost
cost(EXPENSES_SHIP_RUN
, this->GetRunningCost() * this->running_ticks
/ (DAYS_IN_YEAR
* DAY_TICKS
));
239 this->profit_this_year
-= cost
.GetCost();
240 this->running_ticks
= 0;
242 SubtractMoneyFromCompanyFract(this->owner
, cost
);
244 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
245 /* we need this for the profit */
246 SetWindowClassesDirty(WC_SHIPS_LIST
);
249 Trackdir
Ship::GetVehicleTrackdir() const
251 if (this->vehstatus
& VS_CRASHED
) return INVALID_TRACKDIR
;
253 if (this->IsInDepot()) {
254 /* We'll assume the ship is facing outwards */
255 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile
));
258 if (this->state
== TRACK_BIT_WORMHOLE
) {
259 /* ship on aqueduct, so just use his direction and assume a diagonal track */
260 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
263 return TrackDirectionToTrackdir(FindFirstTrack(this->state
), this->direction
);
266 void Ship::MarkDirty()
268 this->colourmap
= PAL_NONE
;
269 this->UpdateViewport(true, false);
273 static void PlayShipSound(const Vehicle
*v
)
275 if (!PlayVehicleSound(v
, VSE_START
)) {
276 SndPlayVehicleFx(ShipVehInfo(v
->engine_type
)->sfx
, v
);
280 void Ship::PlayLeaveStationSound() const
285 TileIndex
Ship::GetOrderStationLocation(StationID station
)
287 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
289 const Station
*st
= Station::Get(station
);
290 if (st
->HasFacilities(FACIL_DOCK
)) {
293 this->IncrementRealOrderIndex();
298 void Ship::UpdateDeltaXY(Direction direction
)
300 static const int8 _delta_xy_table
[8][4] = {
301 /* y_extent, x_extent, y_offs, x_offs */
302 { 6, 6, -3, -3}, // N
303 { 6, 32, -3, -16}, // NE
304 { 6, 6, -3, -3}, // E
305 {32, 6, -16, -3}, // SE
306 { 6, 6, -3, -3}, // S
307 { 6, 32, -3, -16}, // SW
308 { 6, 6, -3, -3}, // W
309 {32, 6, -16, -3}, // NW
312 const int8
*bb
= _delta_xy_table
[direction
];
313 this->x_offs
= bb
[3];
314 this->y_offs
= bb
[2];
315 this->x_extent
= bb
[1];
316 this->y_extent
= bb
[0];
320 static bool CheckShipLeaveDepot(Ship
*v
)
322 if (!v
->IsChainInDepot()) return false;
324 if (v
->current_order
.IsWaitTimetabled())
325 v
->HandleWaiting(false);
326 if (v
->current_order
.IsType(OT_WAITING
))
329 /* We are leaving a depot, but have to go to the exact same one; re-enter */
330 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
331 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
332 VehicleEnterDepot(v
);
336 TileIndex tile
= v
->tile
;
337 Axis axis
= GetShipDepotAxis(tile
);
339 DiagDirection north_dir
= ReverseDiagDir(AxisToDiagDir(axis
));
340 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
341 DiagDirection south_dir
= AxisToDiagDir(axis
);
342 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
344 TrackBits north_tracks
= DiagdirReachesTracks(north_dir
) & GetTileShipTrackStatus(north_neighbour
);
345 TrackBits south_tracks
= DiagdirReachesTracks(south_dir
) & GetTileShipTrackStatus(south_neighbour
);
346 if (north_tracks
&& south_tracks
) {
347 /* Ask pathfinder for best direction */
348 bool reverse
= false;
350 switch (_settings_game
.pf
.pathfinder_for_ships
) {
351 case VPF_OPF
: reverse
= OPFShipChooseTrack(v
, north_neighbour
, north_dir
, north_tracks
, path_found
) == INVALID_TRACK
; break; // OPF always allows reversing
352 case VPF_NPF
: reverse
= NPFShipCheckReverse(v
); break;
353 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
); break;
354 default: NOT_REACHED();
356 if (reverse
) north_tracks
= TRACK_BIT_NONE
;
360 /* Leave towards north */
361 v
->direction
= DiagDirToDir(north_dir
);
362 } else if (south_tracks
) {
363 /* Leave towards south */
364 v
->direction
= DiagDirToDir(south_dir
);
366 /* Both ways blocked */
370 v
->state
= AxisToTrackBits(axis
);
371 v
->vehstatus
&= ~VS_HIDDEN
;
374 v
->UpdateViewport(true, true);
375 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
378 VehicleServiceInDepot(v
);
379 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
380 SetWindowClassesDirty(WC_SHIPS_LIST
);
385 static bool ShipAccelerate(Vehicle
*v
)
390 spd
= min(v
->cur_speed
+ 1, v
->vcache
.cached_max_speed
);
391 spd
= min(spd
, v
->current_order
.GetMaxSpeed() * 2);
393 /* updates statusbar only if speed have changed to save CPU time */
394 if (spd
!= v
->cur_speed
) {
396 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
399 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
400 spd
= v
->GetOldAdvanceSpeed(spd
);
402 if (spd
== 0) return false;
403 if ((byte
)++spd
== 0) return true;
405 v
->progress
= (t
= v
->progress
) - (byte
)spd
;
407 return (t
< v
->progress
);
411 * Ship arrives at a dock. If it is the first time, send out a news item.
412 * @param v Ship that arrived.
413 * @param st Station being visited.
415 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
417 /* Check if station was ever visited before */
418 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
419 st
->had_vehicle_of_type
|= HVOT_SHIP
;
421 SetDParam(0, st
->index
);
423 STR_NEWS_FIRST_SHIP_ARRIVAL
,
424 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
428 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
429 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
435 * Runs the pathfinder to choose a track to continue along.
437 * @param v Ship to navigate
438 * @param tile Tile, the ship is about to enter
439 * @param enterdir Direction of entering
440 * @param tracks Available track choices on \a tile
441 * @return Track to choose, or INVALID_TRACK when to reverse.
443 static Track
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackBits tracks
)
445 assert(IsValidDiagDirection(enterdir
));
447 bool path_found
= true;
449 switch (_settings_game
.pf
.pathfinder_for_ships
) {
450 case VPF_OPF
: track
= OPFShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
451 case VPF_NPF
: track
= NPFShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
452 case VPF_YAPF
: track
= YapfShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
); break;
453 default: NOT_REACHED();
456 v
->HandlePathfindingResult(path_found
);
460 static inline TrackBits
GetAvailShipTracks(TileIndex tile
, DiagDirection dir
)
462 return GetTileShipTrackStatus(tile
) & DiagdirReachesTracks(dir
);
465 static const byte _ship_subcoord
[4][6][3] = {
500 /** Temporary data storage for testing collisions. */
501 struct ShipCollideChecker
{
502 TrackBits track_bits
; ///< Pathfinder chosen track converted to trackbits, or is v->state of requesting ship. (one bit set)
503 TileIndex search_tile
; ///< The tile that we really want to check.
504 Ship
*v
; ///< Ship we are testing for collision.
507 /** Helper function for collision avoidance. */
508 static Vehicle
*FindShipOnTile(Vehicle
*v
, void *data
)
510 if (v
->type
!= VEH_SHIP
) return nullptr;
512 ShipCollideChecker
*scc
= (ShipCollideChecker
*)data
;
514 /* Don't detect vehicles on different parallel tracks. */
515 TrackBits bits
= scc
->track_bits
| Ship::From(v
)->state
;
516 if (bits
== TRACK_BIT_HORZ
|| bits
== TRACK_BIT_VERT
) return nullptr;
518 /* Don't detect ships passing on aquaduct. */
519 if (abs(v
->z_pos
- scc
->v
->z_pos
) >= 8) return nullptr;
521 /* Only requested tiles are checked. avoid desync. */
522 if (TileVirtXY(v
->x_pos
, v
->y_pos
) != scc
->search_tile
) return nullptr;
528 * Adjust speed while on aqueducts.
529 * @param search_tile Tile that the requesting ship will check, one will be added to look in front of the bow.
530 * @param ramp Ramp tile from aqueduct.
531 * @param v Ship that does the request.
532 * @return Allways false.
534 static bool HandleSpeedOnAqueduct(Ship
*v
, TileIndex tile
, TileIndex ramp
)
536 TileIndexDiffC ti
= TileIndexDiffCByDir(v
->direction
);
538 ShipCollideChecker scc
;
540 scc
.track_bits
= TRACK_BIT_NONE
;
541 scc
.search_tile
= TileAddWrap(tile
, ti
.x
, ti
.y
);
543 if (scc
.search_tile
== INVALID_TILE
) return false;
545 if (IsValidTile(scc
.search_tile
) &&
546 (HasVehicleOnPos(ramp
, &scc
, FindShipOnTile
) ||
547 HasVehicleOnPos(GetOtherTunnelBridgeEnd(ramp
), &scc
, FindShipOnTile
))) {
554 * If there is imminent collision or worse, direction and speed will be adjusted.
555 * @param tile Tile that the ship is about to enter.
556 * @param v Ship that does the request.
557 * @param tracks The available tracks that could be followed.
558 * @param track_old The track that the pathfinder assigned.
559 * @param diagdir The DiagDirection that tile will be entered.
560 * @return The new track if found.
562 static void CheckDistanceBetweenShips(TileIndex tile
, Ship
*v
, TrackBits tracks
, Track
*track_old
, DiagDirection diagdir
)
564 if (DistanceManhattan(v
->dest_tile
, tile
) <= 3 && !v
->current_order
.IsType(OT_GOTO_WAYPOINT
)) return; // No checking close to docks and depots.
566 Track track
= *track_old
;
567 TrackBits track_bits
= TrackToTrackBits(track
);
569 /* Only check for collision when pathfinder did not change direction.
570 * This is done in order to keep ships moving towards the intended target. */
571 TrackBits combine
= (v
->state
| track_bits
);
572 if (combine
!= TRACK_BIT_HORZ
&& combine
!= TRACK_BIT_VERT
&& combine
!= track_bits
) return;
575 ShipCollideChecker scc
;
577 scc
.track_bits
= track_bits
;
578 scc
.search_tile
= tile
;
580 bool found
= HasVehicleOnPos(tile
, &scc
, FindShipOnTile
);
583 /* Bridge entrance */
584 if (IsBridgeTile(tile
) && HandleSpeedOnAqueduct(v
, tile
, tile
)) return;
586 scc
.track_bits
= v
->state
;
587 ti
= TileIndexDiffCByDiagDir(_ship_search_directions
[track
][diagdir
]);
588 scc
.search_tile
= TileAddWrap(tile
, ti
.x
, ti
.y
);
589 if (scc
.search_tile
== INVALID_TILE
) return;
591 found
= HasVehicleOnPos(scc
.search_tile
, &scc
, FindShipOnTile
);
595 scc
.track_bits
= track_bits
;
596 ti
= TileIndexDiffCByDiagDir(diagdir
);
597 scc
.search_tile
= TileAddWrap(scc
.search_tile
, ti
.x
, ti
.y
);
598 if (scc
.search_tile
== INVALID_TILE
) return;
600 found
= HasVehicleOnPos(scc
.search_tile
, &scc
, FindShipOnTile
);
605 /* Speed adjustment related to distance. */
606 v
->cur_speed
/= scc
.search_tile
== tile
? 8 : 2;
608 /* Clean none wanted trackbits, including pathfinder track, TRACK_BIT_WORMHOLE and no 90 degree turns. */
609 tracks
= IsDiagonalTrack(track
) ? KillFirstBit(tracks
) : (tracks
& TRACK_BIT_CROSS
);
611 /* Just follow track 1 tile and see if there is a track to follow. (try not to bang in coast or ship) */
612 while (tracks
!= TRACK_BIT_NONE
) {
613 track
= RemoveFirstTrack(&tracks
);
615 ti
= TileIndexDiffCByDiagDir(_ship_search_directions
[track
][diagdir
]);
616 TileIndex tile_check
= TileAddWrap(tile
, ti
.x
, ti
.y
);
617 if (tile_check
== INVALID_TILE
) continue;
619 if (HasVehicleOnPos(tile_check
, &scc
, FindShipOnTile
)) continue;
621 TrackBits bits
= GetAvailShipTracks(tile_check
, _ship_search_directions
[track
][diagdir
]);
622 if (!IsDiagonalTrack(track
)) bits
&= TRACK_BIT_CROSS
; // No 90 degree turns.
624 if (bits
!= INVALID_TRACK_BIT
&& bits
!= TRACK_BIT_NONE
) {
632 static void ShipController(Ship
*v
)
641 v
->current_order_time
++;
643 if (v
->HandleBreakdown()) return;
645 if (v
->vehstatus
& VS_STOPPED
) return;
650 if (v
->current_order
.IsType(OT_LOADING
)) return;
652 if (CheckShipLeaveDepot(v
)) return;
654 v
->ShowVisualEffect();
656 if (!ShipAccelerate(v
)) return;
658 GetNewVehiclePosResult gp
= GetNewVehiclePos(v
);
659 if (v
->state
!= TRACK_BIT_WORMHOLE
) {
660 /* Not on a bridge */
661 if (gp
.old_tile
== gp
.new_tile
) {
662 /* Staying in tile */
663 if (v
->IsInDepot()) {
667 /* Not inside depot */
668 r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
669 if (HasBit(r
, VETS_CANNOT_ENTER
)) goto reverse_direction
;
671 /* A leave station order only needs one tick to get processed, so we can
672 * always skip ahead. */
673 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
674 v
->current_order
.Free();
675 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
676 } else if (v
->dest_tile
!= 0) {
677 /* We have a target, let's see if we reached it... */
678 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
679 DistanceManhattan(v
->dest_tile
, gp
.new_tile
) <= 3) {
680 /* We got within 3 tiles of our target buoy, so let's skip to our
682 UpdateVehicleTimetable(v
, true);
683 v
->IncrementRealOrderIndex();
684 v
->current_order
.MakeDummy();
685 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
686 if (v
->dest_tile
== gp
.new_tile
&& (gp
.x
& 0xF) == 8 && (gp
.y
& 0xF) == 8) {
687 VehicleEnterDepot(v
);
690 } else if (v
->current_order
.IsType(OT_GOTO_STATION
)) {
691 Station
*st
= Station::Get(v
->current_order
.GetDestination());
692 if (st
->IsDockingTile(gp
.new_tile
)) {
693 v
->last_station_visited
= v
->current_order
.GetDestination();
695 /* Process station in the orderlist. */
696 if (st
->facilities
& FACIL_DOCK
) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
697 ShipArrivesAt(v
, st
);
699 } else { // leave stations without docks right aways
700 v
->current_order
.MakeLeaveStation();
701 v
->IncrementRealOrderIndex();
709 if (!IsValidTile(gp
.new_tile
)) goto reverse_direction
;
711 DiagDirection diagdir
= DiagdirBetweenTiles(gp
.old_tile
, gp
.new_tile
);
712 assert(diagdir
!= INVALID_DIAGDIR
);
713 tracks
= GetAvailShipTracks(gp
.new_tile
, diagdir
);
714 if (tracks
== TRACK_BIT_NONE
) goto reverse_direction
;
716 /* Choose a direction, and continue if we find one */
717 track
= ChooseShipTrack(v
, gp
.new_tile
, diagdir
, tracks
);
718 if (track
== INVALID_TRACK
) goto reverse_direction
;
720 /* Try to avoid collision and keep distance between ships. */
721 CheckDistanceBetweenShips(gp
.new_tile
, v
, tracks
, &track
, diagdir
);
723 b
= _ship_subcoord
[diagdir
][track
];
725 gp
.x
= (gp
.x
& ~0xF) | b
[0];
726 gp
.y
= (gp
.y
& ~0xF) | b
[1];
728 /* Call the landscape function and tell it that the vehicle entered the tile */
729 r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
730 if (HasBit(r
, VETS_CANNOT_ENTER
)) goto reverse_direction
;
732 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) {
733 v
->tile
= gp
.new_tile
;
734 v
->state
= TrackToTrackBits(track
);
736 /* Update ship cache when the water class changes. Aqueducts are always canals. */
737 WaterClass old_wc
= GetEffectiveWaterClass(gp
.old_tile
);
738 WaterClass new_wc
= GetEffectiveWaterClass(gp
.new_tile
);
739 if (old_wc
!= new_wc
) v
->UpdateCache();
742 v
->direction
= (Direction
)b
[2];
746 if (!IsTileType(gp
.new_tile
, MP_TUNNELBRIDGE
) || !HasBit(VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
), VETS_ENTERED_WORMHOLE
)) {
747 if (gp
.new_tile
!= TileVirtXY(v
->x_pos
, v
->y_pos
)) HandleSpeedOnAqueduct(v
, gp
.new_tile
, v
->tile
);
751 if ((v
->vehstatus
& VS_HIDDEN
) == 0) v
->Vehicle::UpdateViewport(true);
756 if (gp
.new_tile
!= TileVirtXY(v
->x_pos
, v
->y_pos
)) HandleSpeedOnAqueduct(v
, gp
.new_tile
, v
->tile
);
759 /* update image of ship, as well as delta XY */
762 v
->z_pos
= GetSlopePixelZ(gp
.x
, gp
.y
);
766 v
->UpdateViewport(true, true);
770 dir
= ReverseDir(v
->direction
);
777 if (!((this->vehstatus
& VS_STOPPED
) || this->IsChainInDepot())) this->running_ticks
++;
779 ShipController(this);
786 * @param tile tile of the depot where ship is built.
787 * @param flags type of operation.
788 * @param e the engine to build.
789 * @param data unused.
790 * @param ret[out] the vehicle that has been built.
791 * @return the cost of this operation or an error.
793 CommandCost
CmdBuildShip(TileIndex tile
, DoCommandFlag flags
, const Engine
*e
, uint16 data
, Vehicle
**ret
)
795 tile
= GetShipDepotNorthTile(tile
);
796 if (flags
& DC_EXEC
) {
800 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
802 Ship
*v
= new Ship();
805 v
->owner
= _current_company
;
807 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
808 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
811 v
->z_pos
= GetSlopePixelZ(x
, y
);
813 v
->UpdateDeltaXY(v
->direction
);
814 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
816 v
->spritenum
= svi
->image_index
;
817 v
->cargo_type
= e
->GetDefaultCargoType();
818 v
->cargo_cap
= svi
->capacity
;
821 v
->last_station_visited
= INVALID_STATION
;
822 v
->last_loading_station
= INVALID_STATION
;
823 v
->engine_type
= e
->index
;
825 v
->reliability
= e
->reliability
;
826 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
827 v
->max_age
= e
->GetLifeLengthInDays();
828 _new_vehicle_id
= v
->index
;
830 v
->state
= TRACK_BIT_DEPOT
;
832 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
833 v
->date_of_last_service
= _date
;
834 v
->build_year
= _cur_year
;
835 v
->sprite_seq
.Set(SPR_IMG_QUERY
);
836 v
->random_bits
= VehicleRandomBits();
840 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
841 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
843 v
->InvalidateNewGRFCacheOfChain();
845 v
->cargo_cap
= e
->DetermineCapacity(v
);
847 v
->InvalidateNewGRFCacheOfChain();
852 return CommandCost();
855 bool Ship::FindClosestDepot(TileIndex
*location
, DestinationID
*destination
, bool *reverse
)
857 const Depot
*depot
= FindClosestShipDepot(this, 0);
859 if (depot
== nullptr) return false;
861 if (location
!= nullptr) *location
= depot
->xy
;
862 if (destination
!= nullptr) *destination
= depot
->index
;