Fix: Don't try to rename OWNER_DEITY signs in-game (#9716)
[openttd-github.git] / src / ship_cmd.cpp
blob7f9dab0f1a25c03d0ceadee3a4014fb1974683a7
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 CheckReverseShip(const Ship *v, Trackdir *trackdir = nullptr)
340 /* Ask pathfinder for best direction */
341 bool reverse = false;
342 switch (_settings_game.pf.pathfinder_for_ships) {
343 case VPF_NPF: reverse = NPFShipCheckReverse(v, trackdir); break;
344 case VPF_YAPF: reverse = YapfShipCheckReverse(v, trackdir); break;
345 default: NOT_REACHED();
347 return reverse;
350 static bool CheckShipLeaveDepot(Ship *v)
352 if (!v->IsChainInDepot()) return false;
354 /* We are leaving a depot, but have to go to the exact same one; re-enter */
355 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
356 IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
357 VehicleEnterDepot(v);
358 return true;
361 /* Don't leave depot if no destination set */
362 if (v->dest_tile == 0) return true;
364 /* Don't leave depot if another vehicle is already entering/leaving */
365 /* This helps avoid CPU load if many ships are set to start at the same time */
366 if (HasVehicleOnPos(v->tile, nullptr, &EnsureNoMovingShipProc)) return true;
368 TileIndex tile = v->tile;
369 Axis axis = GetShipDepotAxis(tile);
371 DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
372 TileIndex north_neighbour = TILE_ADD(tile, TileOffsByDiagDir(north_dir));
373 DiagDirection south_dir = AxisToDiagDir(axis);
374 TileIndex south_neighbour = TILE_ADD(tile, 2 * TileOffsByDiagDir(south_dir));
376 TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
377 TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
378 if (north_tracks && south_tracks) {
379 if (CheckReverseShip(v)) north_tracks = TRACK_BIT_NONE;
382 if (north_tracks) {
383 /* Leave towards north */
384 v->rotation = v->direction = DiagDirToDir(north_dir);
385 } else if (south_tracks) {
386 /* Leave towards south */
387 v->rotation = v->direction = DiagDirToDir(south_dir);
388 } else {
389 /* Both ways blocked */
390 return false;
393 v->state = AxisToTrackBits(axis);
394 v->vehstatus &= ~VS_HIDDEN;
396 v->cur_speed = 0;
397 v->UpdateViewport(true, true);
398 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
400 PlayShipSound(v);
401 VehicleServiceInDepot(v);
402 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
403 SetWindowClassesDirty(WC_SHIPS_LIST);
405 return false;
408 static bool ShipAccelerate(Vehicle *v)
410 uint spd;
411 byte t;
413 spd = std::min<uint>(v->cur_speed + 1, v->vcache.cached_max_speed);
414 spd = std::min<uint>(spd, v->current_order.GetMaxSpeed() * 2);
416 /* updates statusbar only if speed have changed to save CPU time */
417 if (spd != v->cur_speed) {
418 v->cur_speed = spd;
419 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
422 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
423 spd = v->GetOldAdvanceSpeed(spd);
425 if (spd == 0) return false;
426 if ((byte)++spd == 0) return true;
428 v->progress = (t = v->progress) - (byte)spd;
430 return (t < v->progress);
434 * Ship arrives at a dock. If it is the first time, send out a news item.
435 * @param v Ship that arrived.
436 * @param st Station being visited.
438 static void ShipArrivesAt(const Vehicle *v, Station *st)
440 /* Check if station was ever visited before */
441 if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
442 st->had_vehicle_of_type |= HVOT_SHIP;
444 SetDParam(0, st->index);
445 AddVehicleNewsItem(
446 STR_NEWS_FIRST_SHIP_ARRIVAL,
447 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
448 v->index,
449 st->index
451 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
452 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
458 * Runs the pathfinder to choose a track to continue along.
460 * @param v Ship to navigate
461 * @param tile Tile, the ship is about to enter
462 * @param enterdir Direction of entering
463 * @param tracks Available track choices on \a tile
464 * @return Track to choose, or INVALID_TRACK when to reverse.
466 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
468 assert(IsValidDiagDirection(enterdir));
470 bool path_found = true;
471 Track track;
473 if (v->dest_tile == 0) {
474 /* No destination, don't invoke pathfinder. */
475 track = TrackBitsToTrack(v->state);
476 if (!IsDiagonalTrack(track)) track = TrackToOppositeTrack(track);
477 if (!HasBit(tracks, track)) track = FindFirstTrack(tracks);
478 path_found = false;
479 } else {
480 /* Attempt to follow cached path. */
481 if (!v->path.empty()) {
482 track = TrackdirToTrack(v->path.front());
484 if (HasBit(tracks, track)) {
485 v->path.pop_front();
486 /* HandlePathfindResult() is not called here because this is not a new pathfinder result. */
487 return track;
490 /* Cached path is invalid so continue with pathfinder. */
491 v->path.clear();
494 switch (_settings_game.pf.pathfinder_for_ships) {
495 case VPF_NPF: track = NPFShipChooseTrack(v, path_found); break;
496 case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found, v->path); break;
497 default: NOT_REACHED();
501 v->HandlePathfindingResult(path_found);
502 return track;
506 * Get the available water tracks on a tile for a ship entering a tile.
507 * @param tile The tile about to enter.
508 * @param dir The entry direction.
509 * @return The available trackbits on the next tile.
511 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
513 TrackBits tracks = GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
515 return tracks;
518 static const byte _ship_subcoord[4][6][3] = {
520 {15, 8, 1},
521 { 0, 0, 0},
522 { 0, 0, 0},
523 {15, 8, 2},
524 {15, 7, 0},
525 { 0, 0, 0},
528 { 0, 0, 0},
529 { 8, 0, 3},
530 { 7, 0, 2},
531 { 0, 0, 0},
532 { 8, 0, 4},
533 { 0, 0, 0},
536 { 0, 8, 5},
537 { 0, 0, 0},
538 { 0, 7, 6},
539 { 0, 0, 0},
540 { 0, 0, 0},
541 { 0, 8, 4},
544 { 0, 0, 0},
545 { 8, 15, 7},
546 { 0, 0, 0},
547 { 8, 15, 6},
548 { 0, 0, 0},
549 { 7, 15, 0},
554 * Test if a ship is in the centre of a lock and should move up or down.
555 * @param v Ship being tested.
556 * @return 0 if ship is not moving in lock, or -1 to move down, 1 to move up.
558 static int ShipTestUpDownOnLock(const Ship *v)
560 /* Suitable tile? */
561 if (!IsTileType(v->tile, MP_WATER) || !IsLock(v->tile) || GetLockPart(v->tile) != LOCK_PART_MIDDLE) return 0;
563 /* Must be at the centre of the lock */
564 if ((v->x_pos & 0xF) != 8 || (v->y_pos & 0xF) != 8) return 0;
566 DiagDirection diagdir = GetInclinedSlopeDirection(GetTileSlope(v->tile));
567 assert(IsValidDiagDirection(diagdir));
569 if (DirToDiagDir(v->direction) == diagdir) {
570 /* Move up */
571 return (v->z_pos < GetTileMaxZ(v->tile) * (int)TILE_HEIGHT) ? 1 : 0;
572 } else {
573 /* Move down */
574 return (v->z_pos > GetTileZ(v->tile) * (int)TILE_HEIGHT) ? -1 : 0;
579 * Test and move a ship up or down in a lock.
580 * @param v Ship to move.
581 * @return true iff ship is moving up or down in a lock.
583 static bool ShipMoveUpDownOnLock(Ship *v)
585 /* Moving up/down through lock */
586 int dz = ShipTestUpDownOnLock(v);
587 if (dz == 0) return false;
589 if (v->cur_speed != 0) {
590 v->cur_speed = 0;
591 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
594 if ((v->tick_counter & 7) == 0) {
595 v->z_pos += dz;
596 v->UpdatePosition();
597 v->UpdateViewport(true, true);
600 return true;
604 * Test if a tile is a docking tile for the given station.
605 * @param tile Docking tile to test.
606 * @param station Destination station.
607 * @return true iff docking tile is next to station.
609 bool IsShipDestinationTile(TileIndex tile, StationID station)
611 assert(IsDockingTile(tile));
612 /* Check each tile adjacent to docking tile. */
613 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
614 TileIndex t = tile + TileOffsByDiagDir(d);
615 if (!IsValidTile(t)) continue;
616 if (IsDockTile(t) && GetStationIndex(t) == station && IsValidDockingDirectionForDock(t, d)) return true;
617 if (IsTileType(t, MP_INDUSTRY)) {
618 const Industry *i = Industry::GetByTile(t);
619 if (i->neutral_station != nullptr && i->neutral_station->index == station) return true;
621 if (IsTileType(t, MP_STATION) && IsOilRig(t) && GetStationIndex(t) == station) return true;
623 return false;
626 static void ShipController(Ship *v)
628 uint32 r;
629 const byte *b;
630 Track track;
631 TrackBits tracks;
632 GetNewVehiclePosResult gp;
634 v->tick_counter++;
635 v->current_order_time++;
637 if (v->HandleBreakdown()) return;
639 if (v->vehstatus & VS_STOPPED) return;
641 if (ProcessOrders(v) && CheckReverseShip(v)) goto reverse_direction;
643 v->HandleLoading();
645 if (v->current_order.IsType(OT_LOADING)) return;
647 if (CheckShipLeaveDepot(v)) return;
649 v->ShowVisualEffect();
651 /* Rotating on spot */
652 if (v->direction != v->rotation) {
653 if ((v->tick_counter & 7) == 0) {
654 DirDiff diff = DirDifference(v->direction, v->rotation);
655 v->rotation = ChangeDir(v->rotation, diff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
656 /* Invalidate the sprite cache direction to force recalculation of viewport */
657 v->sprite_cache.last_direction = INVALID_DIR;
658 v->UpdateViewport(true, true);
660 return;
663 if (ShipMoveUpDownOnLock(v)) return;
665 if (!ShipAccelerate(v)) return;
667 gp = GetNewVehiclePos(v);
668 if (v->state != TRACK_BIT_WORMHOLE) {
669 /* Not on a bridge */
670 if (gp.old_tile == gp.new_tile) {
671 /* Staying in tile */
672 if (v->IsInDepot()) {
673 gp.x = v->x_pos;
674 gp.y = v->y_pos;
675 } else {
676 /* Not inside depot */
677 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
678 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
680 /* A leave station order only needs one tick to get processed, so we can
681 * always skip ahead. */
682 if (v->current_order.IsType(OT_LEAVESTATION)) {
683 v->current_order.Free();
684 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
685 /* Test if continuing forward would lead to a dead-end, moving into the dock. */
686 DiagDirection exitdir = VehicleExitDir(v->direction, v->state);
687 TileIndex tile = TileAddByDiagDir(v->tile, exitdir);
688 if (TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0, exitdir)) == TRACK_BIT_NONE) goto reverse_direction;
689 } else if (v->dest_tile != 0) {
690 /* We have a target, let's see if we reached it... */
691 if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
692 DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
693 /* We got within 3 tiles of our target buoy, so let's skip to our
694 * next order */
695 UpdateVehicleTimetable(v, true);
696 v->IncrementRealOrderIndex();
697 v->current_order.MakeDummy();
698 } else if (v->current_order.IsType(OT_GOTO_DEPOT) &&
699 v->dest_tile == gp.new_tile) {
700 /* Depot orders really need to reach the tile */
701 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
702 VehicleEnterDepot(v);
703 return;
705 } else if (v->current_order.IsType(OT_GOTO_STATION) && IsDockingTile(gp.new_tile)) {
706 /* Process station in the orderlist. */
707 Station *st = Station::Get(v->current_order.GetDestination());
708 if (st->docking_station.Contains(gp.new_tile) && IsShipDestinationTile(gp.new_tile, st->index)) {
709 v->last_station_visited = st->index;
710 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
711 ShipArrivesAt(v, st);
712 v->BeginLoading();
713 } else { // leave stations without docks right away
714 v->current_order.MakeLeaveStation();
715 v->IncrementRealOrderIndex();
721 } else {
722 /* New tile */
723 if (!IsValidTile(gp.new_tile)) goto reverse_direction;
725 DiagDirection diagdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
726 assert(diagdir != INVALID_DIAGDIR);
727 tracks = GetAvailShipTracks(gp.new_tile, diagdir);
728 if (tracks == TRACK_BIT_NONE) {
729 Trackdir trackdir = INVALID_TRACKDIR;
730 CheckReverseShip(v, &trackdir);
731 if (trackdir == INVALID_TRACKDIR) goto reverse_direction;
732 static const Direction _trackdir_to_direction[] = {
733 DIR_NE, DIR_SE, DIR_E, DIR_E, DIR_S, DIR_S, INVALID_DIR, INVALID_DIR,
734 DIR_SW, DIR_NW, DIR_W, DIR_W, DIR_N, DIR_N, INVALID_DIR, INVALID_DIR,
736 v->direction = _trackdir_to_direction[trackdir];
737 assert(v->direction != INVALID_DIR);
738 v->state = TrackdirBitsToTrackBits(TrackdirToTrackdirBits(trackdir));
739 goto direction_changed;
742 /* Choose a direction, and continue if we find one */
743 track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
744 if (track == INVALID_TRACK) goto reverse_direction;
746 b = _ship_subcoord[diagdir][track];
748 gp.x = (gp.x & ~0xF) | b[0];
749 gp.y = (gp.y & ~0xF) | b[1];
751 /* Call the landscape function and tell it that the vehicle entered the tile */
752 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
753 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
755 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
756 v->tile = gp.new_tile;
757 v->state = TrackToTrackBits(track);
759 /* Update ship cache when the water class changes. Aqueducts are always canals. */
760 WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
761 WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
762 if (old_wc != new_wc) v->UpdateCache();
765 Direction new_direction = (Direction)b[2];
766 DirDiff diff = DirDifference(new_direction, v->direction);
767 switch (diff) {
768 case DIRDIFF_SAME:
769 case DIRDIFF_45RIGHT:
770 case DIRDIFF_45LEFT:
771 /* Continue at speed */
772 v->rotation = v->direction = new_direction;
773 break;
775 default:
776 /* Stop for rotation */
777 v->cur_speed = 0;
778 v->direction = new_direction;
779 /* Remember our current location to avoid movement glitch */
780 v->rotation_x_pos = v->x_pos;
781 v->rotation_y_pos = v->y_pos;
782 break;
785 } else {
786 /* On a bridge */
787 if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
788 v->x_pos = gp.x;
789 v->y_pos = gp.y;
790 v->UpdatePosition();
791 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
792 return;
795 /* Ship is back on the bridge head, we need to consume its path
796 * cache entry here as we didn't have to choose a ship track. */
797 if (!v->path.empty()) v->path.pop_front();
800 /* update image of ship, as well as delta XY */
801 v->x_pos = gp.x;
802 v->y_pos = gp.y;
804 getout:
805 v->UpdatePosition();
806 v->UpdateViewport(true, true);
807 return;
809 reverse_direction:
810 v->direction = ReverseDir(v->direction);
811 direction_changed:
812 /* Remember our current location to avoid movement glitch */
813 v->rotation_x_pos = v->x_pos;
814 v->rotation_y_pos = v->y_pos;
815 v->cur_speed = 0;
816 v->path.clear();
817 goto getout;
820 bool Ship::Tick()
822 PerformanceAccumulator framerate(PFE_GL_SHIPS);
824 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
826 ShipController(this);
828 return true;
831 void Ship::SetDestTile(TileIndex tile)
833 if (tile == this->dest_tile) return;
834 this->path.clear();
835 this->dest_tile = tile;
839 * Build a ship.
840 * @param tile tile of the depot where ship is built.
841 * @param flags type of operation.
842 * @param e the engine to build.
843 * @param data unused.
844 * @param[out] ret the vehicle that has been built.
845 * @return the cost of this operation or an error.
847 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
849 tile = GetShipDepotNorthTile(tile);
850 if (flags & DC_EXEC) {
851 int x;
852 int y;
854 const ShipVehicleInfo *svi = &e->u.ship;
856 Ship *v = new Ship();
857 *ret = v;
859 v->owner = _current_company;
860 v->tile = tile;
861 x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
862 y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
863 v->x_pos = x;
864 v->y_pos = y;
865 v->z_pos = GetSlopePixelZ(x, y);
867 v->UpdateDeltaXY();
868 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
870 v->spritenum = svi->image_index;
871 v->cargo_type = e->GetDefaultCargoType();
872 v->cargo_cap = svi->capacity;
873 v->refit_cap = 0;
875 v->last_station_visited = INVALID_STATION;
876 v->last_loading_station = INVALID_STATION;
877 v->engine_type = e->index;
879 v->reliability = e->reliability;
880 v->reliability_spd_dec = e->reliability_spd_dec;
881 v->max_age = e->GetLifeLengthInDays();
882 _new_vehicle_id = v->index;
884 v->state = TRACK_BIT_DEPOT;
886 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
887 v->date_of_last_service = _date;
888 v->build_year = _cur_year;
889 v->sprite_cache.sprite_seq.Set(SPR_IMG_QUERY);
890 v->random_bits = VehicleRandomBits();
892 v->UpdateCache();
894 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
895 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
897 v->InvalidateNewGRFCacheOfChain();
899 v->cargo_cap = e->DetermineCapacity(v);
901 v->InvalidateNewGRFCacheOfChain();
903 v->UpdatePosition();
906 return CommandCost();
909 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
911 const Depot *depot = FindClosestShipDepot(this, 0);
913 if (depot == nullptr) return false;
915 if (location != nullptr) *location = depot->xy;
916 if (destination != nullptr) *destination = depot->index;
918 return true;