2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file ship_cmd.cpp Handling of ships. */
12 #include "landscape.h"
13 #include "timetable.h"
14 #include "news_func.h"
15 #include "company_func.h"
16 #include "pathfinder/npf/npf_func.h"
17 #include "depot_base.h"
18 #include "station_base.h"
19 #include "newgrf_engine.h"
20 #include "pathfinder/yapf/yapf.h"
21 #include "pathfinder/yapf/yapf_ship_regions.h"
22 #include "newgrf_sound.h"
23 #include "spritecache.h"
24 #include "strings_func.h"
25 #include "window_func.h"
26 #include "timer/timer_game_calendar.h"
27 #include "timer/timer_game_economy.h"
28 #include "vehicle_func.h"
29 #include "sound_func.h"
31 #include "game/game.hpp"
32 #include "engine_base.h"
33 #include "company_base.h"
34 #include "tunnelbridge_map.h"
35 #include "zoom_func.h"
36 #include "framerate_type.h"
38 #include "industry_map.h"
41 #include "table/strings.h"
43 #include <unordered_set>
45 #include "safeguards.h"
47 /** Max distance in tiles (as the crow flies) to search for depots when user clicks "go to depot". */
48 constexpr int MAX_SHIP_DEPOT_SEARCH_DISTANCE
= 80;
51 * Determine the effective #WaterClass for a ship travelling on a tile.
52 * @param tile Tile of interest
53 * @return the waterclass to be used by the ship.
55 WaterClass
GetEffectiveWaterClass(TileIndex tile
)
57 if (HasTileWaterClass(tile
)) return GetWaterClass(tile
);
58 if (IsTileType(tile
, MP_TUNNELBRIDGE
)) {
59 assert(GetTunnelBridgeTransportType(tile
) == TRANSPORT_WATER
);
60 return WATER_CLASS_CANAL
;
62 if (IsTileType(tile
, MP_RAILWAY
)) {
63 assert(GetRailGroundType(tile
) == RAIL_GROUND_WATER
);
64 return WATER_CLASS_SEA
;
69 static const uint16_t _ship_sprites
[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
72 bool IsValidImageIndex
<VEH_SHIP
>(uint8_t image_index
)
74 return image_index
< lengthof(_ship_sprites
);
77 static inline TrackBits
GetTileShipTrackStatus(TileIndex tile
)
79 return TrackStatusToTrackBits(GetTileTrackStatus(tile
, TRANSPORT_WATER
, 0));
82 static void GetShipIcon(EngineID engine
, EngineImageType image_type
, VehicleSpriteSeq
*result
)
84 const Engine
*e
= Engine::Get(engine
);
85 uint8_t spritenum
= e
->u
.ship
.image_index
;
87 if (is_custom_sprite(spritenum
)) {
88 GetCustomVehicleIcon(engine
, DIR_W
, image_type
, result
);
89 if (result
->IsValid()) return;
91 spritenum
= e
->original_image_index
;
94 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
95 result
->Set(DIR_W
+ _ship_sprites
[spritenum
]);
98 void DrawShipEngine(int left
, int right
, int preferred_x
, int y
, EngineID engine
, PaletteID pal
, EngineImageType image_type
)
100 VehicleSpriteSeq seq
;
101 GetShipIcon(engine
, image_type
, &seq
);
104 seq
.GetBounds(&rect
);
105 preferred_x
= Clamp(preferred_x
,
106 left
- UnScaleGUI(rect
.left
),
107 right
- UnScaleGUI(rect
.right
));
109 seq
.Draw(preferred_x
, y
, pal
, pal
== PALETTE_CRASH
);
113 * Get the size of the sprite of a ship sprite heading west (used for lists).
114 * @param engine The engine to get the sprite from.
115 * @param[out] width The width of the sprite.
116 * @param[out] height The height of the sprite.
117 * @param[out] xoffs Number of pixels to shift the sprite to the right.
118 * @param[out] yoffs Number of pixels to shift the sprite downwards.
119 * @param image_type Context the sprite is used in.
121 void GetShipSpriteSize(EngineID engine
, uint
&width
, uint
&height
, int &xoffs
, int &yoffs
, EngineImageType image_type
)
123 VehicleSpriteSeq seq
;
124 GetShipIcon(engine
, image_type
, &seq
);
127 seq
.GetBounds(&rect
);
129 width
= UnScaleGUI(rect
.Width());
130 height
= UnScaleGUI(rect
.Height());
131 xoffs
= UnScaleGUI(rect
.left
);
132 yoffs
= UnScaleGUI(rect
.top
);
135 void Ship::GetImage(Direction direction
, EngineImageType image_type
, VehicleSpriteSeq
*result
) const
137 uint8_t spritenum
= this->spritenum
;
139 if (image_type
== EIT_ON_MAP
) direction
= this->rotation
;
141 if (is_custom_sprite(spritenum
)) {
142 GetCustomVehicleSprite(this, direction
, image_type
, result
);
143 if (result
->IsValid()) return;
145 spritenum
= this->GetEngine()->original_image_index
;
148 assert(IsValidImageIndex
<VEH_SHIP
>(spritenum
));
149 result
->Set(_ship_sprites
[spritenum
] + direction
);
152 static const Depot
*FindClosestShipDepot(const Vehicle
*v
, uint max_distance
)
154 const int max_region_distance
= (max_distance
/ WATER_REGION_EDGE_LENGTH
) + 1;
156 static std::unordered_set
<int> visited_patch_hashes
;
157 static std::deque
<WaterRegionPatchDesc
> patches_to_search
;
158 visited_patch_hashes
.clear();
159 patches_to_search
.clear();
161 /* Step 1: find a set of reachable Water Region Patches using BFS. */
162 const WaterRegionPatchDesc start_patch
= GetWaterRegionPatchInfo(v
->tile
);
163 patches_to_search
.push_back(start_patch
);
164 visited_patch_hashes
.insert(CalculateWaterRegionPatchHash(start_patch
));
166 while (!patches_to_search
.empty()) {
167 /* Remove first patch from the queue and make it the current patch. */
168 const WaterRegionPatchDesc current_node
= patches_to_search
.front();
169 patches_to_search
.pop_front();
171 /* Add neighbors of the current patch to the search queue. */
172 TVisitWaterRegionPatchCallBack visitFunc
= [&](const WaterRegionPatchDesc
&water_region_patch
) {
173 /* Note that we check the max distance per axis, not the total distance. */
174 if (std::abs(water_region_patch
.x
- start_patch
.x
) > max_region_distance
||
175 std::abs(water_region_patch
.y
- start_patch
.y
) > max_region_distance
) return;
177 const int hash
= CalculateWaterRegionPatchHash(water_region_patch
);
178 if (visited_patch_hashes
.count(hash
) == 0) {
179 visited_patch_hashes
.insert(hash
);
180 patches_to_search
.push_back(water_region_patch
);
184 VisitWaterRegionPatchNeighbors(current_node
, visitFunc
);
187 /* Step 2: Find the closest depot within the reachable Water Region Patches. */
188 const Depot
*best_depot
= nullptr;
189 uint best_dist_sq
= std::numeric_limits
<uint
>::max();
190 for (const Depot
*depot
: Depot::Iterate()) {
191 const TileIndex tile
= depot
->xy
;
192 if (IsShipDepotTile(tile
) && IsTileOwner(tile
, v
->owner
)) {
193 const uint dist_sq
= DistanceSquare(tile
, v
->tile
);
194 if (dist_sq
< best_dist_sq
&& dist_sq
<= max_distance
* max_distance
&&
195 visited_patch_hashes
.count(CalculateWaterRegionPatchHash(GetWaterRegionPatchInfo(tile
))) > 0) {
196 best_dist_sq
= dist_sq
;
205 static void CheckIfShipNeedsService(Vehicle
*v
)
207 if (Company::Get(v
->owner
)->settings
.vehicle
.servint_ships
== 0 || !v
->NeedsAutomaticServicing()) return;
208 if (v
->IsChainInDepot()) {
209 VehicleServiceInDepot(v
);
214 switch (_settings_game
.pf
.pathfinder_for_ships
) {
215 case VPF_NPF
: max_distance
= _settings_game
.pf
.npf
.maximum_go_to_depot_penalty
/ NPF_TILE_LENGTH
; break;
216 case VPF_YAPF
: max_distance
= _settings_game
.pf
.yapf
.maximum_go_to_depot_penalty
/ YAPF_TILE_LENGTH
; break;
217 default: NOT_REACHED();
220 const Depot
*depot
= FindClosestShipDepot(v
, max_distance
);
222 if (depot
== nullptr) {
223 if (v
->current_order
.IsType(OT_GOTO_DEPOT
)) {
224 v
->current_order
.MakeDummy();
225 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
230 v
->current_order
.MakeGoToDepot(depot
->index
, ODTFB_SERVICE
);
231 v
->SetDestTile(depot
->xy
);
232 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
236 * Update the caches of this ship.
238 void Ship::UpdateCache()
240 const ShipVehicleInfo
*svi
= ShipVehInfo(this->engine_type
);
242 /* Get speed fraction for the current water type. Aqueducts are always canals. */
243 bool is_ocean
= GetEffectiveWaterClass(this->tile
) == WATER_CLASS_SEA
;
244 uint raw_speed
= GetVehicleProperty(this, PROP_SHIP_SPEED
, svi
->max_speed
);
245 this->vcache
.cached_max_speed
= svi
->ApplyWaterClassSpeedFrac(raw_speed
, is_ocean
);
247 /* Update cargo aging period. */
248 this->vcache
.cached_cargo_age_period
= GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD
, EngInfo(this->engine_type
)->cargo_age_period
);
250 this->UpdateVisualEffect();
253 Money
Ship::GetRunningCost() const
255 const Engine
*e
= this->GetEngine();
256 uint cost_factor
= GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR
, e
->u
.ship
.running_cost
);
257 return GetPrice(PR_RUNNING_SHIP
, cost_factor
, e
->GetGRF());
260 /** Calendar day handler. */
261 void Ship::OnNewCalendarDay()
266 /** Economy day handler. */
267 void Ship::OnNewEconomyDay()
269 EconomyAgeVehicle(this);
271 if ((++this->day_counter
& 7) == 0) {
272 DecreaseVehicleValue(this);
275 CheckVehicleBreakdown(this);
276 CheckIfShipNeedsService(this);
280 if (this->running_ticks
== 0) return;
282 CommandCost
cost(EXPENSES_SHIP_RUN
, this->GetRunningCost() * this->running_ticks
/ (CalendarTime::DAYS_IN_YEAR
* Ticks::DAY_TICKS
));
284 this->profit_this_year
-= cost
.GetCost();
285 this->running_ticks
= 0;
287 SubtractMoneyFromCompanyFract(this->owner
, cost
);
289 SetWindowDirty(WC_VEHICLE_DETAILS
, this->index
);
290 /* we need this for the profit */
291 SetWindowClassesDirty(WC_SHIPS_LIST
);
294 Trackdir
Ship::GetVehicleTrackdir() const
296 if (this->vehstatus
& VS_CRASHED
) return INVALID_TRACKDIR
;
298 if (this->IsInDepot()) {
299 /* We'll assume the ship is facing outwards */
300 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile
));
303 if (this->state
== TRACK_BIT_WORMHOLE
) {
304 /* ship on aqueduct, so just use its direction and assume a diagonal track */
305 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction
));
308 return TrackDirectionToTrackdir(FindFirstTrack(this->state
), this->direction
);
311 void Ship::MarkDirty()
313 this->colourmap
= PAL_NONE
;
314 this->UpdateViewport(true, false);
318 void Ship::PlayLeaveStationSound(bool force
) const
320 if (PlayVehicleSound(this, VSE_START
, force
)) return;
321 SndPlayVehicleFx(ShipVehInfo(this->engine_type
)->sfx
, this);
324 TileIndex
Ship::GetOrderStationLocation(StationID station
)
326 if (station
== this->last_station_visited
) this->last_station_visited
= INVALID_STATION
;
328 const Station
*st
= Station::Get(station
);
329 if (CanVehicleUseStation(this, st
)) {
332 this->IncrementRealOrderIndex();
337 void Ship::UpdateDeltaXY()
339 static const int8_t _delta_xy_table
[8][4] = {
340 /* y_extent, x_extent, y_offs, x_offs */
341 { 6, 6, -3, -3}, // N
342 { 6, 32, -3, -16}, // NE
343 { 6, 6, -3, -3}, // E
344 {32, 6, -16, -3}, // SE
345 { 6, 6, -3, -3}, // S
346 { 6, 32, -3, -16}, // SW
347 { 6, 6, -3, -3}, // W
348 {32, 6, -16, -3}, // NW
351 const int8_t *bb
= _delta_xy_table
[this->rotation
];
352 this->x_offs
= bb
[3];
353 this->y_offs
= bb
[2];
354 this->x_extent
= bb
[1];
355 this->y_extent
= bb
[0];
358 if (this->direction
!= this->rotation
) {
359 /* If we are rotating, then it is possible the ship was moved to its next position. In that
360 * case, because we are still showing the old direction, the ship will appear to glitch sideways
361 * slightly. We can work around this by applying an additional offset to make the ship appear
362 * where it was before it moved. */
363 this->x_offs
-= this->x_pos
- this->rotation_x_pos
;
364 this->y_offs
-= this->y_pos
- this->rotation_y_pos
;
369 * Test-procedure for HasVehicleOnPos to check for any ships which are visible and not stopped by the player.
371 static Vehicle
*EnsureNoMovingShipProc(Vehicle
*v
, void *)
373 return v
->type
== VEH_SHIP
&& (v
->vehstatus
& (VS_HIDDEN
| VS_STOPPED
)) == 0 ? v
: nullptr;
376 static bool CheckReverseShip(const Ship
*v
, Trackdir
*trackdir
= nullptr)
378 /* Ask pathfinder for best direction */
379 bool reverse
= false;
380 switch (_settings_game
.pf
.pathfinder_for_ships
) {
381 case VPF_NPF
: reverse
= NPFShipCheckReverse(v
, trackdir
); break;
382 case VPF_YAPF
: reverse
= YapfShipCheckReverse(v
, trackdir
); break;
383 default: NOT_REACHED();
388 static bool CheckShipLeaveDepot(Ship
*v
)
390 if (!v
->IsChainInDepot()) return false;
392 /* Check if we should wait here for unbunching. */
393 if (v
->IsWaitingForUnbunching()) return true;
395 /* We are leaving a depot, but have to go to the exact same one; re-enter */
396 if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
397 IsShipDepotTile(v
->tile
) && GetDepotIndex(v
->tile
) == v
->current_order
.GetDestination()) {
398 VehicleEnterDepot(v
);
402 /* Don't leave depot if no destination set */
403 if (v
->dest_tile
== 0) return true;
405 /* Don't leave depot if another vehicle is already entering/leaving */
406 /* This helps avoid CPU load if many ships are set to start at the same time */
407 if (HasVehicleOnPos(v
->tile
, nullptr, &EnsureNoMovingShipProc
)) return true;
409 TileIndex tile
= v
->tile
;
410 Axis axis
= GetShipDepotAxis(tile
);
412 DiagDirection north_dir
= ReverseDiagDir(AxisToDiagDir(axis
));
413 TileIndex north_neighbour
= TILE_ADD(tile
, TileOffsByDiagDir(north_dir
));
414 DiagDirection south_dir
= AxisToDiagDir(axis
);
415 TileIndex south_neighbour
= TILE_ADD(tile
, 2 * TileOffsByDiagDir(south_dir
));
417 TrackBits north_tracks
= DiagdirReachesTracks(north_dir
) & GetTileShipTrackStatus(north_neighbour
);
418 TrackBits south_tracks
= DiagdirReachesTracks(south_dir
) & GetTileShipTrackStatus(south_neighbour
);
419 if (north_tracks
&& south_tracks
) {
420 if (CheckReverseShip(v
)) north_tracks
= TRACK_BIT_NONE
;
424 /* Leave towards north */
425 v
->rotation
= v
->direction
= DiagDirToDir(north_dir
);
426 } else if (south_tracks
) {
427 /* Leave towards south */
428 v
->rotation
= v
->direction
= DiagDirToDir(south_dir
);
430 /* Both ways blocked */
434 v
->state
= AxisToTrackBits(axis
);
435 v
->vehstatus
&= ~VS_HIDDEN
;
438 v
->UpdateViewport(true, true);
439 SetWindowDirty(WC_VEHICLE_DEPOT
, v
->tile
);
441 VehicleServiceInDepot(v
);
442 v
->LeaveUnbunchingDepot();
443 v
->PlayLeaveStationSound();
444 InvalidateWindowData(WC_VEHICLE_DEPOT
, v
->tile
);
445 SetWindowClassesDirty(WC_SHIPS_LIST
);
451 * Accelerates the ship towards its target speed.
452 * @param v Ship to accelerate.
453 * @return Number of steps to move the ship.
455 static uint
ShipAccelerate(Vehicle
*v
)
458 speed
= std::min
<uint
>(v
->cur_speed
+ v
->acceleration
, v
->vcache
.cached_max_speed
);
459 speed
= std::min
<uint
>(speed
, v
->current_order
.GetMaxSpeed() * 2);
461 /* updates statusbar only if speed have changed to save CPU time */
462 if (speed
!= v
->cur_speed
) {
463 v
->cur_speed
= speed
;
464 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
467 const uint advance_speed
= v
->GetAdvanceSpeed(speed
);
468 const uint number_of_steps
= (advance_speed
+ v
->progress
) / v
->GetAdvanceDistance();
469 const uint remainder
= (advance_speed
+ v
->progress
) % v
->GetAdvanceDistance();
470 assert(remainder
<= std::numeric_limits
<byte
>::max());
471 v
->progress
= static_cast<byte
>(remainder
);
472 return number_of_steps
;
476 * Ship arrives at a dock. If it is the first time, send out a news item.
477 * @param v Ship that arrived.
478 * @param st Station being visited.
480 static void ShipArrivesAt(const Vehicle
*v
, Station
*st
)
482 /* Check if station was ever visited before */
483 if (!(st
->had_vehicle_of_type
& HVOT_SHIP
)) {
484 st
->had_vehicle_of_type
|= HVOT_SHIP
;
486 SetDParam(0, st
->index
);
488 STR_NEWS_FIRST_SHIP_ARRIVAL
,
489 (v
->owner
== _local_company
) ? NT_ARRIVAL_COMPANY
: NT_ARRIVAL_OTHER
,
493 AI::NewEvent(v
->owner
, new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
494 Game::NewEvent(new ScriptEventStationFirstVehicle(st
->index
, v
->index
));
500 * Runs the pathfinder to choose a track to continue along.
502 * @param v Ship to navigate
503 * @param tile Tile, the ship is about to enter
504 * @param enterdir Direction of entering
505 * @param tracks Available track choices on \a tile
506 * @return Track to choose, or INVALID_TRACK when to reverse.
508 static Track
ChooseShipTrack(Ship
*v
, TileIndex tile
, DiagDirection enterdir
, TrackBits tracks
)
510 assert(IsValidDiagDirection(enterdir
));
512 bool path_found
= true;
515 if (v
->dest_tile
== 0) {
516 /* No destination, don't invoke pathfinder. */
517 track
= TrackBitsToTrack(v
->state
);
518 if (!IsDiagonalTrack(track
)) track
= TrackToOppositeTrack(track
);
519 if (!HasBit(tracks
, track
)) track
= FindFirstTrack(tracks
);
522 /* Attempt to follow cached path. */
523 if (!v
->path
.empty()) {
524 track
= TrackdirToTrack(v
->path
.front());
526 if (HasBit(tracks
, track
)) {
528 /* HandlePathfindResult() is not called here because this is not a new pathfinder result. */
532 /* Cached path is invalid so continue with pathfinder. */
536 switch (_settings_game
.pf
.pathfinder_for_ships
) {
537 case VPF_NPF
: track
= NPFShipChooseTrack(v
, path_found
); break;
538 case VPF_YAPF
: track
= YapfShipChooseTrack(v
, tile
, enterdir
, tracks
, path_found
, v
->path
); break;
539 default: NOT_REACHED();
543 v
->HandlePathfindingResult(path_found
);
548 * Get the available water tracks on a tile for a ship entering a tile.
549 * @param tile The tile about to enter.
550 * @param dir The entry direction.
551 * @return The available trackbits on the next tile.
553 static inline TrackBits
GetAvailShipTracks(TileIndex tile
, DiagDirection dir
)
555 TrackBits tracks
= GetTileShipTrackStatus(tile
) & DiagdirReachesTracks(dir
);
560 /** Structure for ship sub-coordinate data for moving into a new tile via a Diagdir onto a Track. */
561 struct ShipSubcoordData
{
562 byte x_subcoord
; ///< New X sub-coordinate on the new tile
563 byte y_subcoord
; ///< New Y sub-coordinate on the new tile
564 Direction dir
; ///< New Direction to move in on the new track
566 /** Ship sub-coordinate data for moving into a new tile via a Diagdir onto a Track.
567 * Array indexes are Diagdir, Track.
568 * There will always be three possible tracks going into an adjacent tile via a Diagdir,
569 * so each Diagdir sub-array will have three valid and three invalid structures per Track.
571 static const ShipSubcoordData _ship_subcoord
[DIAGDIR_END
][TRACK_END
] = {
574 {15, 8, DIR_NE
}, // TRACK_X
575 { 0, 0, INVALID_DIR
}, // TRACK_Y
576 { 0, 0, INVALID_DIR
}, // TRACK_UPPER
577 {15, 8, DIR_E
}, // TRACK_LOWER
578 {15, 7, DIR_N
}, // TRACK_LEFT
579 { 0, 0, INVALID_DIR
}, // TRACK_RIGHT
583 { 0, 0, INVALID_DIR
}, // TRACK_X
584 { 8, 0, DIR_SE
}, // TRACK_Y
585 { 7, 0, DIR_E
}, // TRACK_UPPER
586 { 0, 0, INVALID_DIR
}, // TRACK_LOWER
587 { 8, 0, DIR_S
}, // TRACK_LEFT
588 { 0, 0, INVALID_DIR
}, // TRACK_RIGHT
592 { 0, 8, DIR_SW
}, // TRACK_X
593 { 0, 0, INVALID_DIR
}, // TRACK_Y
594 { 0, 7, DIR_W
}, // TRACK_UPPER
595 { 0, 0, INVALID_DIR
}, // TRACK_LOWER
596 { 0, 0, INVALID_DIR
}, // TRACK_LEFT
597 { 0, 8, DIR_S
}, // TRACK_RIGHT
601 { 0, 0, INVALID_DIR
}, // TRACK_X
602 { 8, 15, DIR_NW
}, // TRACK_Y
603 { 0, 0, INVALID_DIR
}, // TRACK_UPPER
604 { 8, 15, DIR_W
}, // TRACK_LOWER
605 { 0, 0, INVALID_DIR
}, // TRACK_LEFT
606 { 7, 15, DIR_N
}, // TRACK_RIGHT
611 * Test if a ship is in the centre of a lock and should move up or down.
612 * @param v Ship being tested.
613 * @return 0 if ship is not moving in lock, or -1 to move down, 1 to move up.
615 static int ShipTestUpDownOnLock(const Ship
*v
)
618 if (!IsTileType(v
->tile
, MP_WATER
) || !IsLock(v
->tile
) || GetLockPart(v
->tile
) != LOCK_PART_MIDDLE
) return 0;
620 /* Must be at the centre of the lock */
621 if ((v
->x_pos
& 0xF) != 8 || (v
->y_pos
& 0xF) != 8) return 0;
623 DiagDirection diagdir
= GetInclinedSlopeDirection(GetTileSlope(v
->tile
));
624 assert(IsValidDiagDirection(diagdir
));
626 if (DirToDiagDir(v
->direction
) == diagdir
) {
628 return (v
->z_pos
< GetTileMaxZ(v
->tile
) * (int)TILE_HEIGHT
) ? 1 : 0;
631 return (v
->z_pos
> GetTileZ(v
->tile
) * (int)TILE_HEIGHT
) ? -1 : 0;
636 * Test and move a ship up or down in a lock.
637 * @param v Ship to move.
638 * @return true iff ship is moving up or down in a lock.
640 static bool ShipMoveUpDownOnLock(Ship
*v
)
642 /* Moving up/down through lock */
643 int dz
= ShipTestUpDownOnLock(v
);
644 if (dz
== 0) return false;
646 if (v
->cur_speed
!= 0) {
648 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
651 if ((v
->tick_counter
& 7) == 0) {
654 v
->UpdateViewport(true, true);
661 * Test if a tile is a docking tile for the given station.
662 * @param tile Docking tile to test.
663 * @param station Destination station.
664 * @return true iff docking tile is next to station.
666 bool IsShipDestinationTile(TileIndex tile
, StationID station
)
668 assert(IsDockingTile(tile
));
669 /* Check each tile adjacent to docking tile. */
670 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
671 TileIndex t
= tile
+ TileOffsByDiagDir(d
);
672 if (!IsValidTile(t
)) continue;
673 if (IsDockTile(t
) && GetStationIndex(t
) == station
&& IsDockWaterPart(t
)) return true;
674 if (IsTileType(t
, MP_INDUSTRY
)) {
675 const Industry
*i
= Industry::GetByTile(t
);
676 if (i
->neutral_station
!= nullptr && i
->neutral_station
->index
== station
) return true;
678 if (IsTileType(t
, MP_STATION
) && IsOilRig(t
) && GetStationIndex(t
) == station
) return true;
683 static void ReverseShipIntoTrackdir(Ship
*v
, Trackdir trackdir
)
685 static constexpr Direction _trackdir_to_direction
[] = {
686 DIR_NE
, DIR_SE
, DIR_E
, DIR_E
, DIR_S
, DIR_S
, INVALID_DIR
, INVALID_DIR
,
687 DIR_SW
, DIR_NW
, DIR_W
, DIR_W
, DIR_N
, DIR_N
, INVALID_DIR
, INVALID_DIR
,
690 v
->direction
= _trackdir_to_direction
[trackdir
];
691 assert(v
->direction
!= INVALID_DIR
);
692 v
->state
= TrackdirBitsToTrackBits(TrackdirToTrackdirBits(trackdir
));
694 /* Remember our current location to avoid movement glitch */
695 v
->rotation_x_pos
= v
->x_pos
;
696 v
->rotation_y_pos
= v
->y_pos
;
701 v
->UpdateViewport(true, true);
704 static void ReverseShip(Ship
*v
)
706 v
->direction
= ReverseDir(v
->direction
);
708 /* Remember our current location to avoid movement glitch */
709 v
->rotation_x_pos
= v
->x_pos
;
710 v
->rotation_y_pos
= v
->y_pos
;
715 v
->UpdateViewport(true, true);
718 static void ShipController(Ship
*v
)
721 v
->current_order_time
++;
723 if (v
->HandleBreakdown()) return;
725 if (v
->vehstatus
& VS_STOPPED
) return;
727 if (ProcessOrders(v
) && CheckReverseShip(v
)) return ReverseShip(v
);
731 if (v
->current_order
.IsType(OT_LOADING
)) return;
733 if (CheckShipLeaveDepot(v
)) return;
735 v
->ShowVisualEffect();
737 /* Rotating on spot */
738 if (v
->direction
!= v
->rotation
) {
739 if ((v
->tick_counter
& 7) == 0) {
740 DirDiff diff
= DirDifference(v
->direction
, v
->rotation
);
741 v
->rotation
= ChangeDir(v
->rotation
, diff
> DIRDIFF_REVERSE
? DIRDIFF_45LEFT
: DIRDIFF_45RIGHT
);
742 /* Invalidate the sprite cache direction to force recalculation of viewport */
743 v
->sprite_cache
.last_direction
= INVALID_DIR
;
744 v
->UpdateViewport(true, true);
749 if (ShipMoveUpDownOnLock(v
)) return;
751 const uint number_of_steps
= ShipAccelerate(v
);
752 for (uint i
= 0; i
< number_of_steps
; ++i
) {
753 if (ShipMoveUpDownOnLock(v
)) return;
755 GetNewVehiclePosResult gp
= GetNewVehiclePos(v
);
756 if (v
->state
!= TRACK_BIT_WORMHOLE
) {
757 /* Not on a bridge */
758 if (gp
.old_tile
== gp
.new_tile
) {
759 /* Staying in tile */
760 if (v
->IsInDepot()) {
764 /* Not inside depot */
765 const VehicleEnterTileStatus r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
766 if (HasBit(r
, VETS_CANNOT_ENTER
)) return ReverseShip(v
);
768 /* A leave station order only needs one tick to get processed, so we can
769 * always skip ahead. */
770 if (v
->current_order
.IsType(OT_LEAVESTATION
)) {
771 v
->current_order
.Free();
772 SetWindowWidgetDirty(WC_VEHICLE_VIEW
, v
->index
, WID_VV_START_STOP
);
773 /* Test if continuing forward would lead to a dead-end, moving into the dock. */
774 const DiagDirection exitdir
= VehicleExitDir(v
->direction
, v
->state
);
775 const TileIndex tile
= TileAddByDiagDir(v
->tile
, exitdir
);
776 if (TrackStatusToTrackBits(GetTileTrackStatus(tile
, TRANSPORT_WATER
, 0, exitdir
)) == TRACK_BIT_NONE
) return ReverseShip(v
);
777 } else if (v
->dest_tile
!= 0) {
778 /* We have a target, let's see if we reached it... */
779 if (v
->current_order
.IsType(OT_GOTO_WAYPOINT
) &&
780 DistanceManhattan(v
->dest_tile
, gp
.new_tile
) <= 3) {
781 /* We got within 3 tiles of our target buoy, so let's skip to our
783 UpdateVehicleTimetable(v
, true);
784 v
->IncrementRealOrderIndex();
785 v
->current_order
.MakeDummy();
786 } else if (v
->current_order
.IsType(OT_GOTO_DEPOT
) &&
787 v
->dest_tile
== gp
.new_tile
) {
788 /* Depot orders really need to reach the tile */
789 if ((gp
.x
& 0xF) == 8 && (gp
.y
& 0xF) == 8) {
790 VehicleEnterDepot(v
);
793 } else if (v
->current_order
.IsType(OT_GOTO_STATION
) && IsDockingTile(gp
.new_tile
)) {
794 /* Process station in the orderlist. */
795 Station
*st
= Station::Get(v
->current_order
.GetDestination());
796 if (st
->docking_station
.Contains(gp
.new_tile
) && IsShipDestinationTile(gp
.new_tile
, st
->index
)) {
797 v
->last_station_visited
= st
->index
;
798 if (st
->facilities
& FACIL_DOCK
) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
799 ShipArrivesAt(v
, st
);
801 } else { // leave stations without docks right away
802 v
->current_order
.MakeLeaveStation();
803 v
->IncrementRealOrderIndex();
811 if (!IsValidTile(gp
.new_tile
)) return ReverseShip(v
);
813 const DiagDirection diagdir
= DiagdirBetweenTiles(gp
.old_tile
, gp
.new_tile
);
814 assert(diagdir
!= INVALID_DIAGDIR
);
815 const TrackBits tracks
= GetAvailShipTracks(gp
.new_tile
, diagdir
);
816 if (tracks
== TRACK_BIT_NONE
) {
817 Trackdir trackdir
= INVALID_TRACKDIR
;
818 CheckReverseShip(v
, &trackdir
);
819 if (trackdir
== INVALID_TRACKDIR
) return ReverseShip(v
);
820 return ReverseShipIntoTrackdir(v
, trackdir
);
823 /* Choose a direction, and continue if we find one */
824 const Track track
= ChooseShipTrack(v
, gp
.new_tile
, diagdir
, tracks
);
825 if (track
== INVALID_TRACK
) return ReverseShip(v
);
827 const ShipSubcoordData
&b
= _ship_subcoord
[diagdir
][track
];
829 gp
.x
= (gp
.x
& ~0xF) | b
.x_subcoord
;
830 gp
.y
= (gp
.y
& ~0xF) | b
.y_subcoord
;
832 /* Call the landscape function and tell it that the vehicle entered the tile */
833 const VehicleEnterTileStatus r
= VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
);
834 if (HasBit(r
, VETS_CANNOT_ENTER
)) return ReverseShip(v
);
836 if (!HasBit(r
, VETS_ENTERED_WORMHOLE
)) {
837 v
->tile
= gp
.new_tile
;
838 v
->state
= TrackToTrackBits(track
);
840 /* Update ship cache when the water class changes. Aqueducts are always canals. */
841 if (GetEffectiveWaterClass(gp
.old_tile
) != GetEffectiveWaterClass(gp
.new_tile
)) v
->UpdateCache();
844 const Direction new_direction
= b
.dir
;
845 const DirDiff diff
= DirDifference(new_direction
, v
->direction
);
848 case DIRDIFF_45RIGHT
:
850 /* Continue at speed */
851 v
->rotation
= v
->direction
= new_direction
;
855 /* Stop for rotation */
857 v
->direction
= new_direction
;
858 /* Remember our current location to avoid movement glitch */
859 v
->rotation_x_pos
= v
->x_pos
;
860 v
->rotation_y_pos
= v
->y_pos
;
866 if (!IsTileType(gp
.new_tile
, MP_TUNNELBRIDGE
) || !HasBit(VehicleEnterTile(v
, gp
.new_tile
, gp
.x
, gp
.y
), VETS_ENTERED_WORMHOLE
)) {
870 if ((v
->vehstatus
& VS_HIDDEN
) == 0) v
->Vehicle::UpdateViewport(true);
874 /* Ship is back on the bridge head, we need to consume its path
875 * cache entry here as we didn't have to choose a ship track. */
876 if (!v
->path
.empty()) v
->path
.pop_front();
879 /* update image of ship, as well as delta XY */
884 v
->UpdateViewport(true, true);
890 PerformanceAccumulator
framerate(PFE_GL_SHIPS
);
892 if (!(this->vehstatus
& VS_STOPPED
)) this->running_ticks
++;
894 ShipController(this);
899 void Ship::SetDestTile(TileIndex tile
)
901 if (tile
== this->dest_tile
) return;
903 this->dest_tile
= tile
;
908 * @param flags type of operation.
909 * @param tile tile of the depot where ship is built.
910 * @param e the engine to build.
911 * @param[out] ret the vehicle that has been built.
912 * @return the cost of this operation or an error.
914 CommandCost
CmdBuildShip(DoCommandFlag flags
, TileIndex tile
, const Engine
*e
, Vehicle
**ret
)
916 tile
= GetShipDepotNorthTile(tile
);
917 if (flags
& DC_EXEC
) {
921 const ShipVehicleInfo
*svi
= &e
->u
.ship
;
923 Ship
*v
= new Ship();
926 v
->owner
= _current_company
;
928 x
= TileX(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
929 y
= TileY(tile
) * TILE_SIZE
+ TILE_SIZE
/ 2;
932 v
->z_pos
= GetSlopePixelZ(x
, y
);
935 v
->vehstatus
= VS_HIDDEN
| VS_STOPPED
| VS_DEFPAL
;
937 v
->spritenum
= svi
->image_index
;
938 v
->cargo_type
= e
->GetDefaultCargoType();
939 assert(IsValidCargoID(v
->cargo_type
));
940 v
->cargo_cap
= svi
->capacity
;
943 v
->last_station_visited
= INVALID_STATION
;
944 v
->last_loading_station
= INVALID_STATION
;
945 v
->engine_type
= e
->index
;
947 v
->reliability
= e
->reliability
;
948 v
->reliability_spd_dec
= e
->reliability_spd_dec
;
949 v
->max_age
= e
->GetLifeLengthInDays();
951 v
->state
= TRACK_BIT_DEPOT
;
953 v
->SetServiceInterval(Company::Get(_current_company
)->settings
.vehicle
.servint_ships
);
954 v
->date_of_last_service
= TimerGameEconomy::date
;
955 v
->date_of_last_service_newgrf
= TimerGameCalendar::date
;
956 v
->build_year
= TimerGameCalendar::year
;
957 v
->sprite_cache
.sprite_seq
.Set(SPR_IMG_QUERY
);
958 v
->random_bits
= Random();
960 v
->acceleration
= svi
->acceleration
;
963 if (e
->flags
& ENGINE_EXCLUSIVE_PREVIEW
) SetBit(v
->vehicle_flags
, VF_BUILT_AS_PROTOTYPE
);
964 v
->SetServiceIntervalIsPercent(Company::Get(_current_company
)->settings
.vehicle
.servint_ispercent
);
966 v
->InvalidateNewGRFCacheOfChain();
968 v
->cargo_cap
= e
->DetermineCapacity(v
);
970 v
->InvalidateNewGRFCacheOfChain();
975 return CommandCost();
978 ClosestDepot
Ship::FindClosestDepot()
980 const Depot
*depot
= FindClosestShipDepot(this, MAX_SHIP_DEPOT_SEARCH_DISTANCE
);
981 if (depot
== nullptr) return ClosestDepot();
983 return ClosestDepot(depot
->xy
, depot
->index
);