Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / ship_cmd.cpp
blob415d97ebce28962a0e4b55f4c2d93d23a21398b0
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 "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 "newgrf_sound.h"
22 #include "spritecache.h"
23 #include "strings_func.h"
24 #include "window_func.h"
25 #include "date_func.h"
26 #include "vehicle_func.h"
27 #include "sound_func.h"
28 #include "ai/ai.hpp"
29 #include "game/game.hpp"
30 #include "engine_base.h"
31 #include "company_base.h"
32 #include "tunnelbridge_map.h"
33 #include "zoom_func.h"
34 #include "framerate_type.h"
35 #include "industry.h"
36 #include "industry_map.h"
38 #include "table/strings.h"
40 #include "safeguards.h"
42 /**
43 * Determine the effective #WaterClass for a ship travelling on a tile.
44 * @param tile Tile of interest
45 * @return the waterclass to be used by the ship.
47 WaterClass GetEffectiveWaterClass(TileIndex tile)
49 if (HasTileWaterClass(tile)) return GetWaterClass(tile);
50 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
51 assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_WATER);
52 return WATER_CLASS_CANAL;
54 if (IsTileType(tile, MP_RAILWAY)) {
55 assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
56 return WATER_CLASS_SEA;
58 NOT_REACHED();
61 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
63 template <>
64 bool IsValidImageIndex<VEH_SHIP>(uint8 image_index)
66 return image_index < lengthof(_ship_sprites);
69 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
71 return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
74 static void GetShipIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
76 const Engine *e = Engine::Get(engine);
77 uint8 spritenum = e->u.ship.image_index;
79 if (is_custom_sprite(spritenum)) {
80 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
81 if (result->IsValid()) return;
83 spritenum = e->original_image_index;
86 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
87 result->Set(DIR_W + _ship_sprites[spritenum]);
90 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
92 VehicleSpriteSeq seq;
93 GetShipIcon(engine, image_type, &seq);
95 Rect rect;
96 seq.GetBounds(&rect);
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 Rect rect;
119 seq.GetBounds(&rect);
121 width = UnScaleGUI(rect.right - rect.left + 1);
122 height = UnScaleGUI(rect.bottom - rect.top + 1);
123 xoffs = UnScaleGUI(rect.left);
124 yoffs = UnScaleGUI(rect.top);
127 void Ship::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
129 uint8 spritenum = this->spritenum;
131 if (image_type == EIT_ON_MAP) direction = this->rotation;
133 if (is_custom_sprite(spritenum)) {
134 GetCustomVehicleSprite(this, direction, image_type, result);
135 if (result->IsValid()) return;
137 spritenum = this->GetEngine()->original_image_index;
140 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
141 result->Set(_ship_sprites[spritenum] + direction);
144 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
146 /* Find the closest depot */
147 const Depot *best_depot = nullptr;
148 /* If we don't have a maximum distance, i.e. distance = 0,
149 * we want to find any depot so the best distance of no
150 * depot must be more than any correct distance. On the
151 * other hand if we have set a maximum distance, any depot
152 * further away than max_distance can safely be ignored. */
153 uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
155 for (const Depot *depot : Depot::Iterate()) {
156 TileIndex tile = depot->xy;
157 if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
158 uint dist = DistanceManhattan(tile, v->tile);
159 if (dist < best_dist) {
160 best_dist = dist;
161 best_depot = depot;
166 return best_depot;
169 static void CheckIfShipNeedsService(Vehicle *v)
171 if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
172 if (v->IsChainInDepot()) {
173 VehicleServiceInDepot(v);
174 return;
177 uint max_distance;
178 switch (_settings_game.pf.pathfinder_for_ships) {
179 case VPF_NPF: max_distance = _settings_game.pf.npf.maximum_go_to_depot_penalty / NPF_TILE_LENGTH; break;
180 case VPF_YAPF: max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH; break;
181 default: NOT_REACHED();
184 const Depot *depot = FindClosestShipDepot(v, max_distance);
186 if (depot == nullptr) {
187 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
188 v->current_order.MakeDummy();
189 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
191 return;
194 v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
195 v->SetDestTile(depot->xy);
196 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
200 * Update the caches of this ship.
202 void Ship::UpdateCache()
204 const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
206 /* Get speed fraction for the current water type. Aqueducts are always canals. */
207 bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
208 uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
209 this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
211 /* Update cargo aging period. */
212 this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
214 this->UpdateVisualEffect();
217 Money Ship::GetRunningCost() const
219 const Engine *e = this->GetEngine();
220 uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
221 return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
224 void Ship::OnNewDay()
226 if ((++this->day_counter & 7) == 0) {
227 DecreaseVehicleValue(this);
230 CheckVehicleBreakdown(this);
231 AgeVehicle(this);
232 CheckIfShipNeedsService(this);
234 CheckOrders(this);
236 if (this->running_ticks == 0) return;
238 CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
240 this->profit_this_year -= cost.GetCost();
241 this->running_ticks = 0;
243 SubtractMoneyFromCompanyFract(this->owner, cost);
245 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
246 /* we need this for the profit */
247 SetWindowClassesDirty(WC_SHIPS_LIST);
250 Trackdir Ship::GetVehicleTrackdir() const
252 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
254 if (this->IsInDepot()) {
255 /* We'll assume the ship is facing outwards */
256 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
259 if (this->state == TRACK_BIT_WORMHOLE) {
260 /* ship on aqueduct, so just use its direction and assume a diagonal track */
261 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
264 return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
267 void Ship::MarkDirty()
269 this->colourmap = PAL_NONE;
270 this->UpdateViewport(true, false);
271 this->UpdateCache();
274 static void PlayShipSound(const Vehicle *v)
276 if (!PlayVehicleSound(v, VSE_START)) {
277 SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
281 void Ship::PlayLeaveStationSound() const
283 PlayShipSound(this);
286 TileIndex Ship::GetOrderStationLocation(StationID station)
288 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
290 const Station *st = Station::Get(station);
291 if (CanVehicleUseStation(this, st)) {
292 return st->xy;
293 } else {
294 this->IncrementRealOrderIndex();
295 return 0;
299 void Ship::UpdateDeltaXY()
301 static const int8 _delta_xy_table[8][4] = {
302 /* y_extent, x_extent, y_offs, x_offs */
303 { 6, 6, -3, -3}, // N
304 { 6, 32, -3, -16}, // NE
305 { 6, 6, -3, -3}, // E
306 {32, 6, -16, -3}, // SE
307 { 6, 6, -3, -3}, // S
308 { 6, 32, -3, -16}, // SW
309 { 6, 6, -3, -3}, // W
310 {32, 6, -16, -3}, // NW
313 const int8 *bb = _delta_xy_table[this->rotation];
314 this->x_offs = bb[3];
315 this->y_offs = bb[2];
316 this->x_extent = bb[1];
317 this->y_extent = bb[0];
318 this->z_extent = 6;
320 if (this->direction != this->rotation) {
321 /* If we are rotating, then it is possible the ship was moved to its next position. In that
322 * case, because we are still showing the old direction, the ship will appear to glitch sideways
323 * slightly. We can work around this by applying an additional offset to make the ship appear
324 * where it was before it moved. */
325 this->x_offs -= this->x_pos - this->rotation_x_pos;
326 this->y_offs -= this->y_pos - this->rotation_y_pos;
331 * Test-procedure for HasVehicleOnPos to check for any ships which are visible and not stopped by the player.
333 static Vehicle *EnsureNoMovingShipProc(Vehicle *v, void *data)
335 return v->type == VEH_SHIP && (v->vehstatus & (VS_HIDDEN | VS_STOPPED)) == 0 ? v : nullptr;
338 static bool CheckShipLeaveDepot(Ship *v)
340 if (!v->IsChainInDepot()) return false;
342 /* We are leaving a depot, but have to go to the exact same one; re-enter */
343 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
344 IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
345 VehicleEnterDepot(v);
346 return true;
349 /* Don't leave depot if no destination set */
350 if (v->dest_tile == 0) return true;
352 /* Don't leave depot if another vehicle is already entering/leaving */
353 /* This helps avoid CPU load if many ships are set to start at the same time */
354 if (HasVehicleOnPos(v->tile, nullptr, &EnsureNoMovingShipProc)) return true;
356 TileIndex tile = v->tile;
357 Axis axis = GetShipDepotAxis(tile);
359 DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
360 TileIndex north_neighbour = TILE_ADD(tile, TileOffsByDiagDir(north_dir));
361 DiagDirection south_dir = AxisToDiagDir(axis);
362 TileIndex south_neighbour = TILE_ADD(tile, 2 * TileOffsByDiagDir(south_dir));
364 TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
365 TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
366 if (north_tracks && south_tracks) {
367 /* Ask pathfinder for best direction */
368 bool reverse = false;
369 switch (_settings_game.pf.pathfinder_for_ships) {
370 case VPF_NPF: reverse = NPFShipCheckReverse(v); break;
371 case VPF_YAPF: reverse = YapfShipCheckReverse(v); break;
372 default: NOT_REACHED();
374 if (reverse) north_tracks = TRACK_BIT_NONE;
377 if (north_tracks) {
378 /* Leave towards north */
379 v->rotation = v->direction = DiagDirToDir(north_dir);
380 } else if (south_tracks) {
381 /* Leave towards south */
382 v->rotation = v->direction = DiagDirToDir(south_dir);
383 } else {
384 /* Both ways blocked */
385 return false;
388 v->state = AxisToTrackBits(axis);
389 v->vehstatus &= ~VS_HIDDEN;
391 v->cur_speed = 0;
392 v->UpdateViewport(true, true);
393 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
395 PlayShipSound(v);
396 VehicleServiceInDepot(v);
397 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
398 SetWindowClassesDirty(WC_SHIPS_LIST);
400 return false;
403 static bool ShipAccelerate(Vehicle *v)
405 uint spd;
406 byte t;
408 spd = std::min<uint>(v->cur_speed + 1, v->vcache.cached_max_speed);
409 spd = std::min<uint>(spd, v->current_order.GetMaxSpeed() * 2);
411 /* updates statusbar only if speed have changed to save CPU time */
412 if (spd != v->cur_speed) {
413 v->cur_speed = spd;
414 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
417 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
418 spd = v->GetOldAdvanceSpeed(spd);
420 if (spd == 0) return false;
421 if ((byte)++spd == 0) return true;
423 v->progress = (t = v->progress) - (byte)spd;
425 return (t < v->progress);
429 * Ship arrives at a dock. If it is the first time, send out a news item.
430 * @param v Ship that arrived.
431 * @param st Station being visited.
433 static void ShipArrivesAt(const Vehicle *v, Station *st)
435 /* Check if station was ever visited before */
436 if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
437 st->had_vehicle_of_type |= HVOT_SHIP;
439 SetDParam(0, st->index);
440 AddVehicleNewsItem(
441 STR_NEWS_FIRST_SHIP_ARRIVAL,
442 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
443 v->index,
444 st->index
446 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
447 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
453 * Runs the pathfinder to choose a track to continue along.
455 * @param v Ship to navigate
456 * @param tile Tile, the ship is about to enter
457 * @param enterdir Direction of entering
458 * @param tracks Available track choices on \a tile
459 * @return Track to choose, or INVALID_TRACK when to reverse.
461 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
463 assert(IsValidDiagDirection(enterdir));
465 bool path_found = true;
466 Track track;
468 if (v->dest_tile == 0) {
469 /* No destination, don't invoke pathfinder. */
470 track = TrackBitsToTrack(v->state);
471 if (!IsDiagonalTrack(track)) track = TrackToOppositeTrack(track);
472 if (!HasBit(tracks, track)) track = FindFirstTrack(tracks);
473 path_found = false;
474 } else {
475 /* Attempt to follow cached path. */
476 if (!v->path.empty()) {
477 track = TrackdirToTrack(v->path.front());
479 if (HasBit(tracks, track)) {
480 v->path.pop_front();
481 /* HandlePathfindResult() is not called here because this is not a new pathfinder result. */
482 return track;
485 /* Cached path is invalid so continue with pathfinder. */
486 v->path.clear();
489 switch (_settings_game.pf.pathfinder_for_ships) {
490 case VPF_NPF: track = NPFShipChooseTrack(v, path_found); break;
491 case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found, v->path); break;
492 default: NOT_REACHED();
496 v->HandlePathfindingResult(path_found);
497 return track;
501 * Get the available water tracks on a tile for a ship entering a tile.
502 * @param tile The tile about to enter.
503 * @param dir The entry direction.
504 * @return The available trackbits on the next tile.
506 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
508 TrackBits tracks = GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
510 return tracks;
513 static const byte _ship_subcoord[4][6][3] = {
515 {15, 8, 1},
516 { 0, 0, 0},
517 { 0, 0, 0},
518 {15, 8, 2},
519 {15, 7, 0},
520 { 0, 0, 0},
523 { 0, 0, 0},
524 { 8, 0, 3},
525 { 7, 0, 2},
526 { 0, 0, 0},
527 { 8, 0, 4},
528 { 0, 0, 0},
531 { 0, 8, 5},
532 { 0, 0, 0},
533 { 0, 7, 6},
534 { 0, 0, 0},
535 { 0, 0, 0},
536 { 0, 8, 4},
539 { 0, 0, 0},
540 { 8, 15, 7},
541 { 0, 0, 0},
542 { 8, 15, 6},
543 { 0, 0, 0},
544 { 7, 15, 0},
549 * Test if a ship is in the centre of a lock and should move up or down.
550 * @param v Ship being tested.
551 * @return 0 if ship is not moving in lock, or -1 to move down, 1 to move up.
553 static int ShipTestUpDownOnLock(const Ship *v)
555 /* Suitable tile? */
556 if (!IsTileType(v->tile, MP_WATER) || !IsLock(v->tile) || GetLockPart(v->tile) != LOCK_PART_MIDDLE) return 0;
558 /* Must be at the centre of the lock */
559 if ((v->x_pos & 0xF) != 8 || (v->y_pos & 0xF) != 8) return 0;
561 DiagDirection diagdir = GetInclinedSlopeDirection(GetTileSlope(v->tile));
562 assert(IsValidDiagDirection(diagdir));
564 if (DirToDiagDir(v->direction) == diagdir) {
565 /* Move up */
566 return (v->z_pos < GetTileMaxZ(v->tile) * (int)TILE_HEIGHT) ? 1 : 0;
567 } else {
568 /* Move down */
569 return (v->z_pos > GetTileZ(v->tile) * (int)TILE_HEIGHT) ? -1 : 0;
574 * Test and move a ship up or down in a lock.
575 * @param v Ship to move.
576 * @return true iff ship is moving up or down in a lock.
578 static bool ShipMoveUpDownOnLock(Ship *v)
580 /* Moving up/down through lock */
581 int dz = ShipTestUpDownOnLock(v);
582 if (dz == 0) return false;
584 if (v->cur_speed != 0) {
585 v->cur_speed = 0;
586 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
589 if ((v->tick_counter & 7) == 0) {
590 v->z_pos += dz;
591 v->UpdatePosition();
592 v->UpdateViewport(true, true);
595 return true;
599 * Test if a tile is a docking tile for the given station.
600 * @param tile Docking tile to test.
601 * @param station Destination station.
602 * @return true iff docking tile is next to station.
604 bool IsShipDestinationTile(TileIndex tile, StationID station)
606 assert(IsDockingTile(tile));
607 /* Check each tile adjacent to docking tile. */
608 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
609 TileIndex t = tile + TileOffsByDiagDir(d);
610 if (!IsValidTile(t)) continue;
611 if (IsDockTile(t) && GetStationIndex(t) == station && IsValidDockingDirectionForDock(t, d)) return true;
612 if (IsTileType(t, MP_INDUSTRY)) {
613 const Industry *i = Industry::GetByTile(t);
614 if (i->neutral_station != nullptr && i->neutral_station->index == station) return true;
616 if (IsTileType(t, MP_STATION) && IsOilRig(t) && GetStationIndex(t) == station) return true;
618 return false;
621 static void ShipController(Ship *v)
623 uint32 r;
624 const byte *b;
625 Track track;
626 TrackBits tracks;
628 v->tick_counter++;
629 v->current_order_time++;
631 if (v->HandleBreakdown()) return;
633 if (v->vehstatus & VS_STOPPED) return;
635 ProcessOrders(v);
636 v->HandleLoading();
638 if (v->current_order.IsType(OT_LOADING)) return;
640 if (CheckShipLeaveDepot(v)) return;
642 v->ShowVisualEffect();
644 /* Rotating on spot */
645 if (v->direction != v->rotation) {
646 if ((v->tick_counter & 7) == 0) {
647 DirDiff diff = DirDifference(v->direction, v->rotation);
648 v->rotation = ChangeDir(v->rotation, diff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
649 /* Invalidate the sprite cache direction to force recalculation of viewport */
650 v->sprite_cache.last_direction = INVALID_DIR;
651 v->UpdateViewport(true, true);
653 return;
656 if (ShipMoveUpDownOnLock(v)) return;
658 if (!ShipAccelerate(v)) return;
660 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
661 if (v->state != TRACK_BIT_WORMHOLE) {
662 /* Not on a bridge */
663 if (gp.old_tile == gp.new_tile) {
664 /* Staying in tile */
665 if (v->IsInDepot()) {
666 gp.x = v->x_pos;
667 gp.y = v->y_pos;
668 } else {
669 /* Not inside depot */
670 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
671 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
673 /* A leave station order only needs one tick to get processed, so we can
674 * always skip ahead. */
675 if (v->current_order.IsType(OT_LEAVESTATION)) {
676 v->current_order.Free();
677 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
678 /* Test if continuing forward would lead to a dead-end, moving into the dock. */
679 DiagDirection exitdir = VehicleExitDir(v->direction, v->state);
680 TileIndex tile = TileAddByDiagDir(v->tile, exitdir);
681 if (TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0, exitdir)) == TRACK_BIT_NONE) goto reverse_direction;
682 } else if (v->dest_tile != 0) {
683 /* We have a target, let's see if we reached it... */
684 if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
685 DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
686 /* We got within 3 tiles of our target buoy, so let's skip to our
687 * next order */
688 UpdateVehicleTimetable(v, true);
689 v->IncrementRealOrderIndex();
690 v->current_order.MakeDummy();
691 } else if (v->current_order.IsType(OT_GOTO_DEPOT) &&
692 v->dest_tile == gp.new_tile) {
693 /* Depot orders really need to reach the tile */
694 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
695 VehicleEnterDepot(v);
696 return;
698 } else if (v->current_order.IsType(OT_GOTO_STATION) && IsDockingTile(gp.new_tile)) {
699 /* Process station in the orderlist. */
700 Station *st = Station::Get(v->current_order.GetDestination());
701 if (st->docking_station.Contains(gp.new_tile) && IsShipDestinationTile(gp.new_tile, st->index)) {
702 v->last_station_visited = st->index;
703 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
704 ShipArrivesAt(v, st);
705 v->BeginLoading();
706 } else { // leave stations without docks right away
707 v->current_order.MakeLeaveStation();
708 v->IncrementRealOrderIndex();
714 } else {
715 /* New tile */
716 if (!IsValidTile(gp.new_tile)) goto reverse_direction;
718 DiagDirection diagdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
719 assert(diagdir != INVALID_DIAGDIR);
720 tracks = GetAvailShipTracks(gp.new_tile, diagdir);
721 if (tracks == TRACK_BIT_NONE) goto reverse_direction;
723 /* Choose a direction, and continue if we find one */
724 track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
725 if (track == INVALID_TRACK) goto reverse_direction;
727 b = _ship_subcoord[diagdir][track];
729 gp.x = (gp.x & ~0xF) | b[0];
730 gp.y = (gp.y & ~0xF) | b[1];
732 /* Call the landscape function and tell it that the vehicle entered the tile */
733 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
734 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
736 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
737 v->tile = gp.new_tile;
738 v->state = TrackToTrackBits(track);
740 /* Update ship cache when the water class changes. Aqueducts are always canals. */
741 WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
742 WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
743 if (old_wc != new_wc) v->UpdateCache();
746 Direction new_direction = (Direction)b[2];
747 DirDiff diff = DirDifference(new_direction, v->direction);
748 switch (diff) {
749 case DIRDIFF_SAME:
750 case DIRDIFF_45RIGHT:
751 case DIRDIFF_45LEFT:
752 /* Continue at speed */
753 v->rotation = v->direction = new_direction;
754 break;
756 default:
757 /* Stop for rotation */
758 v->cur_speed = 0;
759 v->direction = new_direction;
760 /* Remember our current location to avoid movement glitch */
761 v->rotation_x_pos = v->x_pos;
762 v->rotation_y_pos = v->y_pos;
763 break;
766 } else {
767 /* On a bridge */
768 if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
769 v->x_pos = gp.x;
770 v->y_pos = gp.y;
771 v->UpdatePosition();
772 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
773 return;
776 /* Ship is back on the bridge head, we need to consume its path
777 * cache entry here as we didn't have to choose a ship track. */
778 if (!v->path.empty()) v->path.pop_front();
781 /* update image of ship, as well as delta XY */
782 v->x_pos = gp.x;
783 v->y_pos = gp.y;
785 getout:
786 v->UpdatePosition();
787 v->UpdateViewport(true, true);
788 return;
790 reverse_direction:
791 v->direction = ReverseDir(v->direction);
792 /* Remember our current location to avoid movement glitch */
793 v->rotation_x_pos = v->x_pos;
794 v->rotation_y_pos = v->y_pos;
795 v->cur_speed = 0;
796 v->path.clear();
797 goto getout;
800 bool Ship::Tick()
802 PerformanceAccumulator framerate(PFE_GL_SHIPS);
804 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
806 ShipController(this);
808 return true;
811 void Ship::SetDestTile(TileIndex tile)
813 if (tile == this->dest_tile) return;
814 this->path.clear();
815 this->dest_tile = tile;
819 * Build a ship.
820 * @param tile tile of the depot where ship is built.
821 * @param flags type of operation.
822 * @param e the engine to build.
823 * @param data unused.
824 * @param[out] ret the vehicle that has been built.
825 * @return the cost of this operation or an error.
827 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
829 tile = GetShipDepotNorthTile(tile);
830 if (flags & DC_EXEC) {
831 int x;
832 int y;
834 const ShipVehicleInfo *svi = &e->u.ship;
836 Ship *v = new Ship();
837 *ret = v;
839 v->owner = _current_company;
840 v->tile = tile;
841 x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
842 y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
843 v->x_pos = x;
844 v->y_pos = y;
845 v->z_pos = GetSlopePixelZ(x, y);
847 v->UpdateDeltaXY();
848 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
850 v->spritenum = svi->image_index;
851 v->cargo_type = e->GetDefaultCargoType();
852 v->cargo_cap = svi->capacity;
853 v->refit_cap = 0;
855 v->last_station_visited = INVALID_STATION;
856 v->last_loading_station = INVALID_STATION;
857 v->engine_type = e->index;
859 v->reliability = e->reliability;
860 v->reliability_spd_dec = e->reliability_spd_dec;
861 v->max_age = e->GetLifeLengthInDays();
862 _new_vehicle_id = v->index;
864 v->state = TRACK_BIT_DEPOT;
866 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
867 v->date_of_last_service = _date;
868 v->build_year = _cur_year;
869 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
870 v->random_bits = VehicleRandomBits();
872 v->UpdateCache();
874 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
875 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
877 v->InvalidateNewGRFCacheOfChain();
879 v->cargo_cap = e->DetermineCapacity(v);
881 v->InvalidateNewGRFCacheOfChain();
883 v->UpdatePosition();
886 return CommandCost();
889 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
891 const Depot *depot = FindClosestShipDepot(this, 0);
893 if (depot == nullptr) return false;
895 if (location != nullptr) *location = depot->xy;
896 if (destination != nullptr) *destination = depot->index;
898 return true;