Codechange: Use cached town, station, industry names for list window sorting
[openttd-github.git] / src / ship_cmd.cpp
blob1758454addb28bc8d8a22563f1486e281c89a1be
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 his 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 a ship.
333 static Vehicle *EnsureNoVisibleShipProc(Vehicle *v, void *data)
335 return v->type == VEH_SHIP && (v->vehstatus & VS_HIDDEN) == 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, &EnsureNoVisibleShipProc)) 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 = min(v->cur_speed + 1, v->vcache.cached_max_speed);
409 spd = min(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;
617 return false;
620 static void ShipController(Ship *v)
622 uint32 r;
623 const byte *b;
624 Track track;
625 TrackBits tracks;
627 v->tick_counter++;
628 v->current_order_time++;
630 if (v->HandleBreakdown()) return;
632 if (v->vehstatus & VS_STOPPED) return;
634 ProcessOrders(v);
635 v->HandleLoading();
637 if (v->current_order.IsType(OT_LOADING)) return;
639 if (CheckShipLeaveDepot(v)) return;
641 v->ShowVisualEffect();
643 /* Rotating on spot */
644 if (v->direction != v->rotation) {
645 if ((v->tick_counter & 7) == 0) {
646 DirDiff diff = DirDifference(v->direction, v->rotation);
647 v->rotation = ChangeDir(v->rotation, diff > DIRDIFF_REVERSE ? DIRDIFF_45LEFT : DIRDIFF_45RIGHT);
648 v->UpdateViewport(true, true);
650 return;
653 if (ShipMoveUpDownOnLock(v)) return;
655 if (!ShipAccelerate(v)) return;
657 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
658 if (v->state != TRACK_BIT_WORMHOLE) {
659 /* Not on a bridge */
660 if (gp.old_tile == gp.new_tile) {
661 /* Staying in tile */
662 if (v->IsInDepot()) {
663 gp.x = v->x_pos;
664 gp.y = v->y_pos;
665 } else {
666 /* Not inside depot */
667 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
668 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
670 /* A leave station order only needs one tick to get processed, so we can
671 * always skip ahead. */
672 if (v->current_order.IsType(OT_LEAVESTATION)) {
673 v->current_order.Free();
674 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
675 /* Test if continuing forward would lead to a dead-end, moving into the dock. */
676 DiagDirection exitdir = VehicleExitDir(v->direction, v->state);
677 TileIndex tile = TileAddByDiagDir(v->tile, exitdir);
678 if (TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0, exitdir)) == TRACK_BIT_NONE) goto reverse_direction;
679 } else if (v->dest_tile != 0) {
680 /* We have a target, let's see if we reached it... */
681 if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
682 DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
683 /* We got within 3 tiles of our target buoy, so let's skip to our
684 * next order */
685 UpdateVehicleTimetable(v, true);
686 v->IncrementRealOrderIndex();
687 v->current_order.MakeDummy();
688 } else if (v->current_order.IsType(OT_GOTO_DEPOT) &&
689 v->dest_tile == gp.new_tile) {
690 /* Depot orders really need to reach the tile */
691 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
692 VehicleEnterDepot(v);
693 return;
695 } else if (v->current_order.IsType(OT_GOTO_STATION) && IsDockingTile(gp.new_tile)) {
696 /* Process station in the orderlist. */
697 Station *st = Station::Get(v->current_order.GetDestination());
698 if (st->docking_station.Contains(gp.new_tile) && IsShipDestinationTile(gp.new_tile, st->index)) {
699 v->last_station_visited = st->index;
700 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
701 ShipArrivesAt(v, st);
702 v->BeginLoading();
703 } else { // leave stations without docks right away
704 v->current_order.MakeLeaveStation();
705 v->IncrementRealOrderIndex();
711 } else {
712 /* New tile */
713 if (!IsValidTile(gp.new_tile)) goto reverse_direction;
715 DiagDirection diagdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
716 assert(diagdir != INVALID_DIAGDIR);
717 tracks = GetAvailShipTracks(gp.new_tile, diagdir);
718 if (tracks == TRACK_BIT_NONE) goto reverse_direction;
720 /* Choose a direction, and continue if we find one */
721 track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
722 if (track == INVALID_TRACK) goto reverse_direction;
724 b = _ship_subcoord[diagdir][track];
726 gp.x = (gp.x & ~0xF) | b[0];
727 gp.y = (gp.y & ~0xF) | b[1];
729 /* Call the landscape function and tell it that the vehicle entered the tile */
730 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
731 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
733 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
734 v->tile = gp.new_tile;
735 v->state = TrackToTrackBits(track);
737 /* Update ship cache when the water class changes. Aqueducts are always canals. */
738 WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
739 WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
740 if (old_wc != new_wc) v->UpdateCache();
743 Direction new_direction = (Direction)b[2];
744 DirDiff diff = DirDifference(new_direction, v->direction);
745 switch (diff) {
746 case DIRDIFF_SAME:
747 case DIRDIFF_45RIGHT:
748 case DIRDIFF_45LEFT:
749 /* Continue at speed */
750 v->rotation = v->direction = new_direction;
751 break;
753 default:
754 /* Stop for rotation */
755 v->cur_speed = 0;
756 v->direction = new_direction;
757 /* Remember our current location to avoid movement glitch */
758 v->rotation_x_pos = v->x_pos;
759 v->rotation_y_pos = v->y_pos;
760 break;
763 } else {
764 /* On a bridge */
765 if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
766 v->x_pos = gp.x;
767 v->y_pos = gp.y;
768 v->UpdatePosition();
769 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
770 return;
773 /* Ship is back on the bridge head, we need to consume its path
774 * cache entry here as we didn't have to choose a ship track. */
775 if (!v->path.empty()) v->path.pop_front();
778 /* update image of ship, as well as delta XY */
779 v->x_pos = gp.x;
780 v->y_pos = gp.y;
782 getout:
783 v->UpdatePosition();
784 v->UpdateViewport(true, true);
785 return;
787 reverse_direction:
788 v->direction = ReverseDir(v->direction);
789 /* Remember our current location to avoid movement glitch */
790 v->rotation_x_pos = v->x_pos;
791 v->rotation_y_pos = v->y_pos;
792 v->cur_speed = 0;
793 v->path.clear();
794 goto getout;
797 bool Ship::Tick()
799 PerformanceAccumulator framerate(PFE_GL_SHIPS);
801 if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
803 ShipController(this);
805 return true;
808 void Ship::SetDestTile(TileIndex tile)
810 if (tile == this->dest_tile) return;
811 this->path.clear();
812 this->dest_tile = tile;
816 * Build a ship.
817 * @param tile tile of the depot where ship is built.
818 * @param flags type of operation.
819 * @param e the engine to build.
820 * @param data unused.
821 * @param[out] ret the vehicle that has been built.
822 * @return the cost of this operation or an error.
824 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
826 tile = GetShipDepotNorthTile(tile);
827 if (flags & DC_EXEC) {
828 int x;
829 int y;
831 const ShipVehicleInfo *svi = &e->u.ship;
833 Ship *v = new Ship();
834 *ret = v;
836 v->owner = _current_company;
837 v->tile = tile;
838 x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
839 y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
840 v->x_pos = x;
841 v->y_pos = y;
842 v->z_pos = GetSlopePixelZ(x, y);
844 v->UpdateDeltaXY();
845 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
847 v->spritenum = svi->image_index;
848 v->cargo_type = e->GetDefaultCargoType();
849 v->cargo_cap = svi->capacity;
850 v->refit_cap = 0;
852 v->last_station_visited = INVALID_STATION;
853 v->last_loading_station = INVALID_STATION;
854 v->engine_type = e->index;
856 v->reliability = e->reliability;
857 v->reliability_spd_dec = e->reliability_spd_dec;
858 v->max_age = e->GetLifeLengthInDays();
859 _new_vehicle_id = v->index;
861 v->state = TRACK_BIT_DEPOT;
863 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
864 v->date_of_last_service = _date;
865 v->build_year = _cur_year;
866 v->sprite_seq.Set(SPR_IMG_QUERY);
867 v->random_bits = VehicleRandomBits();
869 v->UpdateCache();
871 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
872 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
874 v->InvalidateNewGRFCacheOfChain();
876 v->cargo_cap = e->DetermineCapacity(v);
878 v->InvalidateNewGRFCacheOfChain();
880 v->UpdatePosition();
883 return CommandCost();
886 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
888 const Depot *depot = FindClosestShipDepot(this, 0);
890 if (depot == nullptr) return false;
892 if (location != nullptr) *location = depot->xy;
893 if (destination != nullptr) *destination = depot->index;
895 return true;