Update: Translations from eints
[openttd-github.git] / src / ship_cmd.cpp
blob3184f3badb0c0bed7a19a5b35af7c7231683d08a
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file ship_cmd.cpp Handling of ships. */
10 #include "stdafx.h"
11 #include "ship.h"
12 #include "landscape.h"
13 #include "timetable.h"
14 #include "news_func.h"
15 #include "company_func.h"
16 #include "depot_base.h"
17 #include "station_base.h"
18 #include "newgrf_engine.h"
19 #include "pathfinder/yapf/yapf.h"
20 #include "pathfinder/yapf/yapf_ship_regions.h"
21 #include "newgrf_sound.h"
22 #include "spritecache.h"
23 #include "strings_func.h"
24 #include "window_func.h"
25 #include "timer/timer_game_calendar.h"
26 #include "timer/timer_game_economy.h"
27 #include "vehicle_func.h"
28 #include "sound_func.h"
29 #include "ai/ai.hpp"
30 #include "game/game.hpp"
31 #include "engine_base.h"
32 #include "company_base.h"
33 #include "tunnelbridge_map.h"
34 #include "zoom_func.h"
35 #include "framerate_type.h"
36 #include "industry.h"
37 #include "industry_map.h"
38 #include "ship_cmd.h"
40 #include "table/strings.h"
42 #include <unordered_set>
44 #include "safeguards.h"
46 /** Max distance in tiles (as the crow flies) to search for depots when user clicks "go to depot". */
47 constexpr int MAX_SHIP_DEPOT_SEARCH_DISTANCE = 80;
49 /**
50 * Determine the effective #WaterClass for a ship travelling on a tile.
51 * @param tile Tile of interest
52 * @return the waterclass to be used by the ship.
54 WaterClass GetEffectiveWaterClass(TileIndex tile)
56 if (HasTileWaterClass(tile)) return GetWaterClass(tile);
57 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
58 assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_WATER);
59 return WATER_CLASS_CANAL;
61 if (IsTileType(tile, MP_RAILWAY)) {
62 assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
63 return WATER_CLASS_SEA;
65 NOT_REACHED();
68 static const uint16_t _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
70 template <>
71 bool IsValidImageIndex<VEH_SHIP>(uint8_t image_index)
73 return image_index < lengthof(_ship_sprites);
76 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
78 return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
81 static void GetShipIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
83 const Engine *e = Engine::Get(engine);
84 uint8_t spritenum = e->u.ship.image_index;
86 if (is_custom_sprite(spritenum)) {
87 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
88 if (result->IsValid()) return;
90 spritenum = e->original_image_index;
93 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
94 result->Set(DIR_W + _ship_sprites[spritenum]);
97 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
99 VehicleSpriteSeq seq;
100 GetShipIcon(engine, image_type, &seq);
102 Rect rect;
103 seq.GetBounds(&rect);
104 preferred_x = Clamp(preferred_x,
105 left - UnScaleGUI(rect.left),
106 right - UnScaleGUI(rect.right));
108 seq.Draw(preferred_x, y, pal, pal == PALETTE_CRASH);
112 * Get the size of the sprite of a ship sprite heading west (used for lists).
113 * @param engine The engine to get the sprite from.
114 * @param[out] width The width of the sprite.
115 * @param[out] height The height of the sprite.
116 * @param[out] xoffs Number of pixels to shift the sprite to the right.
117 * @param[out] yoffs Number of pixels to shift the sprite downwards.
118 * @param image_type Context the sprite is used in.
120 void GetShipSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
122 VehicleSpriteSeq seq;
123 GetShipIcon(engine, image_type, &seq);
125 Rect rect;
126 seq.GetBounds(&rect);
128 width = UnScaleGUI(rect.Width());
129 height = UnScaleGUI(rect.Height());
130 xoffs = UnScaleGUI(rect.left);
131 yoffs = UnScaleGUI(rect.top);
134 void Ship::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
136 uint8_t spritenum = this->spritenum;
138 if (image_type == EIT_ON_MAP) direction = this->rotation;
140 if (is_custom_sprite(spritenum)) {
141 GetCustomVehicleSprite(this, direction, image_type, result);
142 if (result->IsValid()) return;
144 spritenum = this->GetEngine()->original_image_index;
147 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
148 result->Set(_ship_sprites[spritenum] + direction);
151 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
153 const int max_region_distance = (max_distance / WATER_REGION_EDGE_LENGTH) + 1;
155 static std::unordered_set<int> visited_patch_hashes;
156 static std::deque<WaterRegionPatchDesc> patches_to_search;
157 visited_patch_hashes.clear();
158 patches_to_search.clear();
160 /* Step 1: find a set of reachable Water Region Patches using BFS. */
161 const WaterRegionPatchDesc start_patch = GetWaterRegionPatchInfo(v->tile);
162 patches_to_search.push_back(start_patch);
163 visited_patch_hashes.insert(CalculateWaterRegionPatchHash(start_patch));
165 while (!patches_to_search.empty()) {
166 /* Remove first patch from the queue and make it the current patch. */
167 const WaterRegionPatchDesc current_node = patches_to_search.front();
168 patches_to_search.pop_front();
170 /* Add neighbors of the current patch to the search queue. */
171 TVisitWaterRegionPatchCallBack visitFunc = [&](const WaterRegionPatchDesc &water_region_patch) {
172 /* Note that we check the max distance per axis, not the total distance. */
173 if (std::abs(water_region_patch.x - start_patch.x) > max_region_distance ||
174 std::abs(water_region_patch.y - start_patch.y) > max_region_distance) return;
176 const int hash = CalculateWaterRegionPatchHash(water_region_patch);
177 if (visited_patch_hashes.count(hash) == 0) {
178 visited_patch_hashes.insert(hash);
179 patches_to_search.push_back(water_region_patch);
183 VisitWaterRegionPatchNeighbors(current_node, visitFunc);
186 /* Step 2: Find the closest depot within the reachable Water Region Patches. */
187 const Depot *best_depot = nullptr;
188 uint best_dist_sq = std::numeric_limits<uint>::max();
189 for (const Depot *depot : Depot::Iterate()) {
190 const TileIndex tile = depot->xy;
191 if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
192 const uint dist_sq = DistanceSquare(tile, v->tile);
193 if (dist_sq < best_dist_sq && dist_sq <= max_distance * max_distance &&
194 visited_patch_hashes.count(CalculateWaterRegionPatchHash(GetWaterRegionPatchInfo(tile))) > 0) {
195 best_dist_sq = dist_sq;
196 best_depot = depot;
201 return best_depot;
204 static void CheckIfShipNeedsService(Vehicle *v)
206 if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
207 if (v->IsChainInDepot()) {
208 VehicleServiceInDepot(v);
209 return;
212 uint max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH;
214 const Depot *depot = FindClosestShipDepot(v, max_distance);
216 if (depot == nullptr) {
217 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
218 v->current_order.MakeDummy();
219 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
221 return;
224 v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
225 v->SetDestTile(depot->xy);
226 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
230 * Update the caches of this ship.
232 void Ship::UpdateCache()
234 const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
236 /* Get speed fraction for the current water type. Aqueducts are always canals. */
237 bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
238 uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
239 this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
241 /* Update cargo aging period. */
242 this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
244 this->UpdateVisualEffect();
247 Money Ship::GetRunningCost() const
249 const Engine *e = this->GetEngine();
250 uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
251 return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
254 /** Calendar day handler. */
255 void Ship::OnNewCalendarDay()
257 AgeVehicle(this);
260 /** Economy day handler. */
261 void Ship::OnNewEconomyDay()
263 EconomyAgeVehicle(this);
265 if ((++this->day_counter & 7) == 0) {
266 DecreaseVehicleValue(this);
269 CheckVehicleBreakdown(this);
270 CheckIfShipNeedsService(this);
272 CheckOrders(this);
274 if (this->running_ticks == 0) return;
276 CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (CalendarTime::DAYS_IN_YEAR * Ticks::DAY_TICKS));
278 this->profit_this_year -= cost.GetCost();
279 this->running_ticks = 0;
281 SubtractMoneyFromCompanyFract(this->owner, cost);
283 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
284 /* we need this for the profit */
285 SetWindowClassesDirty(WC_SHIPS_LIST);
288 Trackdir Ship::GetVehicleTrackdir() const
290 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
292 if (this->IsInDepot()) {
293 /* We'll assume the ship is facing outwards */
294 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
297 if (this->state == TRACK_BIT_WORMHOLE) {
298 /* ship on aqueduct, so just use its direction and assume a diagonal track */
299 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
302 return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
305 void Ship::MarkDirty()
307 this->colourmap = PAL_NONE;
308 this->UpdateViewport(true, false);
309 this->UpdateCache();
312 void Ship::PlayLeaveStationSound(bool force) const
314 if (PlayVehicleSound(this, VSE_START, force)) return;
315 SndPlayVehicleFx(ShipVehInfo(this->engine_type)->sfx, this);
318 TileIndex Ship::GetOrderStationLocation(StationID station)
320 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
322 const Station *st = Station::Get(station);
323 if (CanVehicleUseStation(this, st)) {
324 return st->xy;
325 } else {
326 this->IncrementRealOrderIndex();
327 return 0;
331 void Ship::UpdateDeltaXY()
333 static const int8_t _delta_xy_table[8][4] = {
334 /* y_extent, x_extent, y_offs, x_offs */
335 { 6, 6, -3, -3}, // N
336 { 6, 32, -3, -16}, // NE
337 { 6, 6, -3, -3}, // E
338 {32, 6, -16, -3}, // SE
339 { 6, 6, -3, -3}, // S
340 { 6, 32, -3, -16}, // SW
341 { 6, 6, -3, -3}, // W
342 {32, 6, -16, -3}, // NW
345 const int8_t *bb = _delta_xy_table[this->rotation];
346 this->x_offs = bb[3];
347 this->y_offs = bb[2];
348 this->x_extent = bb[1];
349 this->y_extent = bb[0];
350 this->z_extent = 6;
352 if (this->direction != this->rotation) {
353 /* If we are rotating, then it is possible the ship was moved to its next position. In that
354 * case, because we are still showing the old direction, the ship will appear to glitch sideways
355 * slightly. We can work around this by applying an additional offset to make the ship appear
356 * where it was before it moved. */
357 this->x_offs -= this->x_pos - this->rotation_x_pos;
358 this->y_offs -= this->y_pos - this->rotation_y_pos;
363 * Test-procedure for HasVehicleOnPos to check for any ships which are moving.
365 static Vehicle *EnsureNoMovingShipProc(Vehicle *v, void *)
367 return v->type == VEH_SHIP && v->cur_speed != 0 ? v : nullptr;
370 static bool CheckReverseShip(const Ship *v, Trackdir *trackdir = nullptr)
372 /* Ask pathfinder for best direction */
373 return YapfShipCheckReverse(v, trackdir);
376 static bool CheckShipLeaveDepot(Ship *v)
378 if (!v->IsChainInDepot()) return false;
380 /* Check if we should wait here for unbunching. */
381 if (v->IsWaitingForUnbunching()) return true;
383 /* We are leaving a depot, but have to go to the exact same one; re-enter */
384 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
385 IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
386 VehicleEnterDepot(v);
387 return true;
390 /* Don't leave depot if no destination set */
391 if (v->dest_tile == 0) return true;
393 /* Don't leave depot if another vehicle is already entering/leaving */
394 /* This helps avoid CPU load if many ships are set to start at the same time */
395 if (HasVehicleOnPos(v->tile, nullptr, &EnsureNoMovingShipProc)) return true;
397 TileIndex tile = v->tile;
398 Axis axis = GetShipDepotAxis(tile);
400 DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
401 TileIndex north_neighbour = TileAdd(tile, TileOffsByDiagDir(north_dir));
402 DiagDirection south_dir = AxisToDiagDir(axis);
403 TileIndex south_neighbour = TileAdd(tile, 2 * TileOffsByDiagDir(south_dir));
405 TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
406 TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
407 if (north_tracks && south_tracks) {
408 if (CheckReverseShip(v)) north_tracks = TRACK_BIT_NONE;
411 if (north_tracks) {
412 /* Leave towards north */
413 v->rotation = v->direction = DiagDirToDir(north_dir);
414 } else if (south_tracks) {
415 /* Leave towards south */
416 v->rotation = v->direction = DiagDirToDir(south_dir);
417 } else {
418 /* Both ways blocked */
419 return false;
422 v->state = AxisToTrackBits(axis);
423 v->vehstatus &= ~VS_HIDDEN;
425 v->cur_speed = 0;
426 v->UpdateViewport(true, true);
427 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
429 VehicleServiceInDepot(v);
430 v->LeaveUnbunchingDepot();
431 v->PlayLeaveStationSound();
432 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
433 SetWindowClassesDirty(WC_SHIPS_LIST);
435 return false;
439 * Accelerates the ship towards its target speed.
440 * @param v Ship to accelerate.
441 * @return Number of steps to move the ship.
443 static uint ShipAccelerate(Vehicle *v)
445 uint speed;
446 speed = std::min<uint>(v->cur_speed + v->acceleration, v->vcache.cached_max_speed);
447 speed = std::min<uint>(speed, v->current_order.GetMaxSpeed() * 2);
449 /* updates statusbar only if speed have changed to save CPU time */
450 if (speed != v->cur_speed) {
451 v->cur_speed = speed;
452 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
455 const uint advance_speed = v->GetAdvanceSpeed(speed);
456 const uint number_of_steps = (advance_speed + v->progress) / v->GetAdvanceDistance();
457 const uint remainder = (advance_speed + v->progress) % v->GetAdvanceDistance();
458 assert(remainder <= std::numeric_limits<uint8_t>::max());
459 v->progress = static_cast<uint8_t>(remainder);
460 return number_of_steps;
464 * Ship arrives at a dock. If it is the first time, send out a news item.
465 * @param v Ship that arrived.
466 * @param st Station being visited.
468 static void ShipArrivesAt(const Vehicle *v, Station *st)
470 /* Check if station was ever visited before */
471 if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
472 st->had_vehicle_of_type |= HVOT_SHIP;
474 SetDParam(0, st->index);
475 AddVehicleNewsItem(
476 STR_NEWS_FIRST_SHIP_ARRIVAL,
477 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
478 v->index,
479 st->index
481 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
482 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
488 * Runs the pathfinder to choose a track to continue along.
490 * @param v Ship to navigate
491 * @param tile Tile, the ship is about to enter
492 * @param tracks Available track choices on \a tile
493 * @return Track to choose, or INVALID_TRACK when to reverse.
495 static Track ChooseShipTrack(Ship *v, TileIndex tile, TrackBits tracks)
497 bool path_found = true;
498 Track track;
500 if (v->dest_tile == 0) {
501 /* No destination, don't invoke pathfinder. */
502 track = TrackBitsToTrack(v->state);
503 if (!IsDiagonalTrack(track)) track = TrackToOppositeTrack(track);
504 if (!HasBit(tracks, track)) track = FindFirstTrack(tracks);
505 path_found = false;
506 } else {
507 /* Attempt to follow cached path. */
508 if (!v->path.empty()) {
509 track = TrackdirToTrack(v->path.front());
511 if (HasBit(tracks, track)) {
512 v->path.pop_front();
513 /* HandlePathfindResult() is not called here because this is not a new pathfinder result. */
514 return track;
517 /* Cached path is invalid so continue with pathfinder. */
518 v->path.clear();
521 track = YapfShipChooseTrack(v, tile, path_found, v->path);
524 v->HandlePathfindingResult(path_found);
525 return track;
529 * Get the available water tracks on a tile for a ship entering a tile.
530 * @param tile The tile about to enter.
531 * @param dir The entry direction.
532 * @return The available trackbits on the next tile.
534 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
536 TrackBits tracks = GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
538 return tracks;
541 /** Structure for ship sub-coordinate data for moving into a new tile via a Diagdir onto a Track. */
542 struct ShipSubcoordData {
543 uint8_t x_subcoord; ///< New X sub-coordinate on the new tile
544 uint8_t y_subcoord; ///< New Y sub-coordinate on the new tile
545 Direction dir; ///< New Direction to move in on the new track
547 /** Ship sub-coordinate data for moving into a new tile via a Diagdir onto a Track.
548 * Array indexes are Diagdir, Track.
549 * There will always be three possible tracks going into an adjacent tile via a Diagdir,
550 * so each Diagdir sub-array will have three valid and three invalid structures per Track.
552 static const ShipSubcoordData _ship_subcoord[DIAGDIR_END][TRACK_END] = {
553 // DIAGDIR_NE
555 {15, 8, DIR_NE}, // TRACK_X
556 { 0, 0, INVALID_DIR}, // TRACK_Y
557 { 0, 0, INVALID_DIR}, // TRACK_UPPER
558 {15, 8, DIR_E}, // TRACK_LOWER
559 {15, 7, DIR_N}, // TRACK_LEFT
560 { 0, 0, INVALID_DIR}, // TRACK_RIGHT
562 // DIAGDIR_SE
564 { 0, 0, INVALID_DIR}, // TRACK_X
565 { 8, 0, DIR_SE}, // TRACK_Y
566 { 7, 0, DIR_E}, // TRACK_UPPER
567 { 0, 0, INVALID_DIR}, // TRACK_LOWER
568 { 8, 0, DIR_S}, // TRACK_LEFT
569 { 0, 0, INVALID_DIR}, // TRACK_RIGHT
571 // DIAGDIR_SW
573 { 0, 8, DIR_SW}, // TRACK_X
574 { 0, 0, INVALID_DIR}, // TRACK_Y
575 { 0, 7, DIR_W}, // TRACK_UPPER
576 { 0, 0, INVALID_DIR}, // TRACK_LOWER
577 { 0, 0, INVALID_DIR}, // TRACK_LEFT
578 { 0, 8, DIR_S}, // TRACK_RIGHT
580 // DIAGDIR_NW
582 { 0, 0, INVALID_DIR}, // TRACK_X
583 { 8, 15, DIR_NW}, // TRACK_Y
584 { 0, 0, INVALID_DIR}, // TRACK_UPPER
585 { 8, 15, DIR_W}, // TRACK_LOWER
586 { 0, 0, INVALID_DIR}, // TRACK_LEFT
587 { 7, 15, DIR_N}, // TRACK_RIGHT
592 * Test if a ship is in the centre of a lock and should move up or down.
593 * @param v Ship being tested.
594 * @return 0 if ship is not moving in lock, or -1 to move down, 1 to move up.
596 static int ShipTestUpDownOnLock(const Ship *v)
598 /* Suitable tile? */
599 if (!IsTileType(v->tile, MP_WATER) || !IsLock(v->tile) || GetLockPart(v->tile) != LOCK_PART_MIDDLE) return 0;
601 /* Must be at the centre of the lock */
602 if ((v->x_pos & 0xF) != 8 || (v->y_pos & 0xF) != 8) return 0;
604 DiagDirection diagdir = GetInclinedSlopeDirection(GetTileSlope(v->tile));
605 assert(IsValidDiagDirection(diagdir));
607 if (DirToDiagDir(v->direction) == diagdir) {
608 /* Move up */
609 return (v->z_pos < GetTileMaxZ(v->tile) * (int)TILE_HEIGHT) ? 1 : 0;
610 } else {
611 /* Move down */
612 return (v->z_pos > GetTileZ(v->tile) * (int)TILE_HEIGHT) ? -1 : 0;
617 * Test and move a ship up or down in a lock.
618 * @param v Ship to move.
619 * @return true iff ship is moving up or down in a lock.
621 static bool ShipMoveUpDownOnLock(Ship *v)
623 /* Moving up/down through lock */
624 int dz = ShipTestUpDownOnLock(v);
625 if (dz == 0) return false;
627 if (v->cur_speed != 0) {
628 v->cur_speed = 0;
629 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
632 if ((v->tick_counter & 7) == 0) {
633 v->z_pos += dz;
634 v->UpdatePosition();
635 v->UpdateViewport(true, true);
638 return true;
642 * Test if a tile is a docking tile for the given station.
643 * @param tile Docking tile to test.
644 * @param station Destination station.
645 * @return true iff docking tile is next to station.
647 bool IsShipDestinationTile(TileIndex tile, StationID station)
649 assert(IsDockingTile(tile));
650 /* Check each tile adjacent to docking tile. */
651 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
652 TileIndex t = tile + TileOffsByDiagDir(d);
653 if (!IsValidTile(t)) continue;
654 if (IsDockTile(t) && GetStationIndex(t) == station && IsDockWaterPart(t)) return true;
655 if (IsTileType(t, MP_INDUSTRY)) {
656 const Industry *i = Industry::GetByTile(t);
657 if (i->neutral_station != nullptr && i->neutral_station->index == station) return true;
659 if (IsTileType(t, MP_STATION) && IsOilRig(t) && GetStationIndex(t) == station) return true;
661 return false;
664 static void ReverseShipIntoTrackdir(Ship *v, Trackdir trackdir)
666 static constexpr Direction _trackdir_to_direction[] = {
667 DIR_NE, DIR_SE, DIR_E, DIR_E, DIR_S, DIR_S, INVALID_DIR, INVALID_DIR,
668 DIR_SW, DIR_NW, DIR_W, DIR_W, DIR_N, DIR_N, INVALID_DIR, INVALID_DIR,
671 v->direction = _trackdir_to_direction[trackdir];
672 assert(v->direction != INVALID_DIR);
673 v->state = TrackdirBitsToTrackBits(TrackdirToTrackdirBits(trackdir));
675 /* Remember our current location to avoid movement glitch */
676 v->rotation_x_pos = v->x_pos;
677 v->rotation_y_pos = v->y_pos;
678 v->cur_speed = 0;
679 v->path.clear();
681 v->UpdatePosition();
682 v->UpdateViewport(true, true);
685 static void ReverseShip(Ship *v)
687 v->direction = ReverseDir(v->direction);
689 /* Remember our current location to avoid movement glitch */
690 v->rotation_x_pos = v->x_pos;
691 v->rotation_y_pos = v->y_pos;
692 v->cur_speed = 0;
693 v->path.clear();
695 v->UpdatePosition();
696 v->UpdateViewport(true, true);
699 static void ShipController(Ship *v)
701 v->tick_counter++;
702 v->current_order_time++;
704 if (v->HandleBreakdown()) return;
706 if (v->vehstatus & VS_STOPPED) return;
708 if (ProcessOrders(v) && CheckReverseShip(v)) return ReverseShip(v);
710 v->HandleLoading();
712 if (v->current_order.IsType(OT_LOADING)) return;
714 if (CheckShipLeaveDepot(v)) return;
716 v->ShowVisualEffect();
718 /* Rotating on spot */
719 if (v->direction != v->rotation) {
720 if ((v->tick_counter & 7) == 0) {
721 DirDiff diff = DirDifference(v->direction, v->rotation);
722 v->rotation = ChangeDir(v->rotation, diff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
723 /* Invalidate the sprite cache direction to force recalculation of viewport */
724 v->sprite_cache.last_direction = INVALID_DIR;
725 v->UpdateViewport(true, true);
727 return;
730 if (ShipMoveUpDownOnLock(v)) return;
732 const uint number_of_steps = ShipAccelerate(v);
733 for (uint i = 0; i < number_of_steps; ++i) {
734 if (ShipMoveUpDownOnLock(v)) return;
736 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
737 if (v->state != TRACK_BIT_WORMHOLE) {
738 /* Not on a bridge */
739 if (gp.old_tile == gp.new_tile) {
740 /* Staying in tile */
741 if (v->IsInDepot()) {
742 gp.x = v->x_pos;
743 gp.y = v->y_pos;
744 } else {
745 /* Not inside depot */
746 const VehicleEnterTileStatus r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
747 if (HasBit(r, VETS_CANNOT_ENTER)) return ReverseShip(v);
749 /* A leave station order only needs one tick to get processed, so we can
750 * always skip ahead. */
751 if (v->current_order.IsType(OT_LEAVESTATION)) {
752 v->current_order.Free();
753 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
754 /* Test if continuing forward would lead to a dead-end, moving into the dock. */
755 const DiagDirection exitdir = VehicleExitDir(v->direction, v->state);
756 const TileIndex tile = TileAddByDiagDir(v->tile, exitdir);
757 if (TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0, exitdir)) == TRACK_BIT_NONE) return ReverseShip(v);
758 } else if (v->dest_tile != 0) {
759 /* We have a target, let's see if we reached it... */
760 if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
761 DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
762 /* We got within 3 tiles of our target buoy, so let's skip to our
763 * next order */
764 UpdateVehicleTimetable(v, true);
765 v->IncrementRealOrderIndex();
766 v->current_order.MakeDummy();
767 } else if (v->current_order.IsType(OT_GOTO_DEPOT) &&
768 v->dest_tile == gp.new_tile) {
769 /* Depot orders really need to reach the tile */
770 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
771 VehicleEnterDepot(v);
772 return;
774 } else if (v->current_order.IsType(OT_GOTO_STATION) && IsDockingTile(gp.new_tile)) {
775 /* Process station in the orderlist. */
776 Station *st = Station::Get(v->current_order.GetDestination());
777 if (st->docking_station.Contains(gp.new_tile) && IsShipDestinationTile(gp.new_tile, st->index)) {
778 v->last_station_visited = st->index;
779 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
780 ShipArrivesAt(v, st);
781 v->BeginLoading();
782 } else { // leave stations without docks right away
783 v->current_order.MakeLeaveStation();
784 v->IncrementRealOrderIndex();
790 } else {
791 /* New tile */
792 if (!IsValidTile(gp.new_tile)) return ReverseShip(v);
794 const DiagDirection diagdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
795 assert(diagdir != INVALID_DIAGDIR);
796 const TrackBits tracks = GetAvailShipTracks(gp.new_tile, diagdir);
797 if (tracks == TRACK_BIT_NONE) {
798 Trackdir trackdir = INVALID_TRACKDIR;
799 CheckReverseShip(v, &trackdir);
800 if (trackdir == INVALID_TRACKDIR) return ReverseShip(v);
801 return ReverseShipIntoTrackdir(v, trackdir);
804 /* Choose a direction, and continue if we find one */
805 const Track track = ChooseShipTrack(v, gp.new_tile, tracks);
806 if (track == INVALID_TRACK) return ReverseShip(v);
808 const ShipSubcoordData &b = _ship_subcoord[diagdir][track];
810 gp.x = (gp.x & ~0xF) | b.x_subcoord;
811 gp.y = (gp.y & ~0xF) | b.y_subcoord;
813 /* Call the landscape function and tell it that the vehicle entered the tile */
814 const VehicleEnterTileStatus r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
815 if (HasBit(r, VETS_CANNOT_ENTER)) return ReverseShip(v);
817 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
818 v->tile = gp.new_tile;
819 v->state = TrackToTrackBits(track);
821 /* Update ship cache when the water class changes. Aqueducts are always canals. */
822 if (GetEffectiveWaterClass(gp.old_tile) != GetEffectiveWaterClass(gp.new_tile)) v->UpdateCache();
825 const Direction new_direction = b.dir;
826 const DirDiff diff = DirDifference(new_direction, v->direction);
827 switch (diff) {
828 case DIRDIFF_SAME:
829 case DIRDIFF_45RIGHT:
830 case DIRDIFF_45LEFT:
831 /* Continue at speed */
832 v->rotation = v->direction = new_direction;
833 break;
835 default:
836 /* Stop for rotation */
837 v->cur_speed = 0;
838 v->direction = new_direction;
839 /* Remember our current location to avoid movement glitch */
840 v->rotation_x_pos = v->x_pos;
841 v->rotation_y_pos = v->y_pos;
842 break;
845 } else {
846 /* On a bridge */
847 if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
848 v->x_pos = gp.x;
849 v->y_pos = gp.y;
850 v->UpdatePosition();
851 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
852 continue;
855 /* Ship is back on the bridge head, we need to consume its path
856 * cache entry here as we didn't have to choose a ship track. */
857 if (!v->path.empty()) v->path.pop_front();
860 /* update image of ship, as well as delta XY */
861 v->x_pos = gp.x;
862 v->y_pos = gp.y;
864 v->UpdatePosition();
865 v->UpdateViewport(true, true);
869 bool Ship::Tick()
871 PerformanceAccumulator framerate(PFE_GL_SHIPS);
873 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
875 ShipController(this);
877 return true;
880 void Ship::SetDestTile(TileIndex tile)
882 if (tile == this->dest_tile) return;
883 this->path.clear();
884 this->dest_tile = tile;
888 * Build a ship.
889 * @param flags type of operation.
890 * @param tile tile of the depot where ship is built.
891 * @param e the engine to build.
892 * @param[out] ret the vehicle that has been built.
893 * @return the cost of this operation or an error.
895 CommandCost CmdBuildShip(DoCommandFlag flags, TileIndex tile, const Engine *e, Vehicle **ret)
897 tile = GetShipDepotNorthTile(tile);
898 if (flags & DC_EXEC) {
899 int x;
900 int y;
902 const ShipVehicleInfo *svi = &e->u.ship;
904 Ship *v = new Ship();
905 *ret = v;
907 v->owner = _current_company;
908 v->tile = tile;
909 x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
910 y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
911 v->x_pos = x;
912 v->y_pos = y;
913 v->z_pos = GetSlopePixelZ(x, y);
915 v->UpdateDeltaXY();
916 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
918 v->spritenum = svi->image_index;
919 v->cargo_type = e->GetDefaultCargoType();
920 assert(IsValidCargoID(v->cargo_type));
921 v->cargo_cap = svi->capacity;
922 v->refit_cap = 0;
924 v->last_station_visited = INVALID_STATION;
925 v->last_loading_station = INVALID_STATION;
926 v->engine_type = e->index;
928 v->reliability = e->reliability;
929 v->reliability_spd_dec = e->reliability_spd_dec;
930 v->max_age = e->GetLifeLengthInDays();
932 v->state = TRACK_BIT_DEPOT;
934 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
935 v->date_of_last_service = TimerGameEconomy::date;
936 v->date_of_last_service_newgrf = TimerGameCalendar::date;
937 v->build_year = TimerGameCalendar::year;
938 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
939 v->random_bits = Random();
941 v->acceleration = svi->acceleration;
942 v->UpdateCache();
944 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
945 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
947 v->InvalidateNewGRFCacheOfChain();
949 v->cargo_cap = e->DetermineCapacity(v);
951 v->InvalidateNewGRFCacheOfChain();
953 v->UpdatePosition();
956 return CommandCost();
959 ClosestDepot Ship::FindClosestDepot()
961 const Depot *depot = FindClosestShipDepot(this, MAX_SHIP_DEPOT_SEARCH_DISTANCE);
962 if (depot == nullptr) return ClosestDepot();
964 return ClosestDepot(depot->xy, depot->index);