Enable ships to pass on both sides of other ships.
[openttd-joker.git] / src / ship_cmd.cpp
blobfe87a1cdea6c87cb7ba4efb6a5212c3ee97fefa4
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file ship_cmd.cpp Handling of ships. */
12 #include "stdafx.h"
13 #include "ship.h"
14 #include "dock_base.h"
15 #include "landscape.h"
16 #include "timetable.h"
17 #include "news_func.h"
18 #include "company_func.h"
19 #include "pathfinder/npf/npf_func.h"
20 #include "depot_base.h"
21 #include "station_base.h"
22 #include "newgrf_engine.h"
23 #include "pathfinder/yapf/yapf.h"
24 #include "newgrf_sound.h"
25 #include "spritecache.h"
26 #include "strings_func.h"
27 #include "window_func.h"
28 #include "date_func.h"
29 #include "vehicle_func.h"
30 #include "sound_func.h"
31 #include "ai/ai.hpp"
32 #include "game/game.hpp"
33 #include "pathfinder/opf/opf_ship.h"
34 #include "engine_base.h"
35 #include "company_base.h"
36 #include "tunnelbridge_map.h"
37 #include "zoom_func.h"
39 #include "table/strings.h"
41 #include "safeguards.h"
43 /**
44 * Determine the effective #WaterClass for a ship travelling on a tile.
45 * @param tile Tile of interest
46 * @return the waterclass to be used by the ship.
48 WaterClass GetEffectiveWaterClass(TileIndex tile)
50 if (HasTileWaterClass(tile)) return GetWaterClass(tile);
51 if (IsTileType(tile, MP_TUNNELBRIDGE)) {
52 assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_WATER);
53 return WATER_CLASS_CANAL;
55 if (IsTileType(tile, MP_RAILWAY)) {
56 assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
57 return WATER_CLASS_SEA;
59 NOT_REACHED();
62 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
64 template <>
65 bool IsValidImageIndex<VEH_SHIP>(uint8 image_index)
67 return image_index < lengthof(_ship_sprites);
70 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
72 return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
75 static void GetShipIcon(EngineID engine, EngineImageType image_type, VehicleSpriteSeq *result)
77 const Engine *e = Engine::Get(engine);
78 uint8 spritenum = e->u.ship.image_index;
80 if (is_custom_sprite(spritenum)) {
81 GetCustomVehicleIcon(engine, DIR_W, image_type, result);
82 if (result->IsValid()) return;
84 spritenum = e->original_image_index;
87 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
88 result->Set(DIR_W + _ship_sprites[spritenum]);
91 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
93 VehicleSpriteSeq seq;
94 GetShipIcon(engine, image_type, &seq);
96 Rect16 rect = seq.GetBounds();
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 Rect16 rect = seq.GetBounds();
120 width = UnScaleGUI(rect.right - rect.left + 1);
121 height = UnScaleGUI(rect.bottom - rect.top + 1);
122 xoffs = UnScaleGUI(rect.left);
123 yoffs = UnScaleGUI(rect.top);
126 void Ship::GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
128 uint8 spritenum = this->spritenum;
130 if (is_custom_sprite(spritenum)) {
131 GetCustomVehicleSprite(this, direction, image_type, result);
132 if (result->IsValid()) return;
134 spritenum = this->GetEngine()->original_image_index;
137 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
138 result->Set(_ship_sprites[spritenum] + direction);
141 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
143 /* Find the closest depot */
144 const Depot *depot;
145 const Depot *best_depot = NULL;
146 /* If we don't have a maximum distance, i.e. distance = 0,
147 * we want to find any depot so the best distance of no
148 * depot must be more than any correct distance. On the
149 * other hand if we have set a maximum distance, any depot
150 * further away than max_distance can safely be ignored. */
151 uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
153 FOR_ALL_DEPOTS(depot) {
154 TileIndex tile = depot->xy;
155 if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
156 uint dist = DistanceManhattan(tile, v->tile);
157 if (dist < best_dist) {
158 best_dist = dist;
159 best_depot = depot;
164 return best_depot;
167 static void CheckIfShipNeedsService(Vehicle *v)
169 if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
170 if (v->IsChainInDepot()) {
171 VehicleServiceInDepot(v);
172 return;
175 uint max_distance;
176 switch (_settings_game.pf.pathfinder_for_ships) {
177 case VPF_OPF: max_distance = 12; break;
178 case VPF_NPF: max_distance = _settings_game.pf.npf.maximum_go_to_depot_penalty / NPF_TILE_LENGTH; break;
179 case VPF_YAPF: max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH; break;
180 default: NOT_REACHED();
183 const Depot *depot = FindClosestShipDepot(v, max_distance);
185 if (depot == NULL) {
186 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
187 v->current_order.MakeDummy();
188 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
190 return;
193 v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
194 v->dest_tile = depot->xy;
195 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
199 * Update the caches of this ship.
201 void Ship::UpdateCache()
203 const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
205 /* Get speed fraction for the current water type. Aqueducts are always canals. */
206 bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
207 uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
208 this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
210 /* Update cargo aging period. */
211 this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
213 this->UpdateVisualEffect();
216 Money Ship::GetRunningCost() const
218 const Engine *e = this->GetEngine();
219 uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
220 return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
223 void Ship::OnNewDay()
225 if ((++this->day_counter & 7) == 0) {
226 DecreaseVehicleValue(this);
229 CheckVehicleBreakdown(this);
230 AgeVehicle(this);
231 CheckIfShipNeedsService(this);
233 CheckOrders(this);
235 if (this->running_ticks == 0) return;
237 CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
239 this->profit_this_year -= cost.GetCost();
240 this->running_ticks = 0;
242 SubtractMoneyFromCompanyFract(this->owner, cost);
244 SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
245 /* we need this for the profit */
246 SetWindowClassesDirty(WC_SHIPS_LIST);
249 Trackdir Ship::GetVehicleTrackdir() const
251 if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
253 if (this->IsInDepot()) {
254 /* We'll assume the ship is facing outwards */
255 return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
258 if (this->state == TRACK_BIT_WORMHOLE) {
259 /* ship on aqueduct, so just use his direction and assume a diagonal track */
260 return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
263 return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
266 void Ship::MarkDirty()
268 this->colourmap = PAL_NONE;
269 this->UpdateViewport(true, false);
270 this->UpdateCache();
273 static void PlayShipSound(const Vehicle *v)
275 if (!PlayVehicleSound(v, VSE_START)) {
276 SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
280 void Ship::PlayLeaveStationSound() const
282 PlayShipSound(this);
286 * Of all the docks a station has, return the best destination for a ship.
287 * @param v The ship.
288 * @param st Station the ship \a v is heading for.
289 * @return The free and closest (if none is free, just closest) dock of station \a st to ship \a v.
291 const Dock* GetBestDock(const Ship *v, const Station *st)
293 assert(st != NULL && st->HasFacilities(FACIL_DOCK) && st->docks != NULL);
294 if (st->docks->next == NULL) return st->docks;
296 Dock *best_dock = NULL;
297 uint best_distance = UINT_MAX;
299 for (Dock *dock = st->docks; dock != NULL; dock = dock->next) {
300 uint new_distance = DistanceManhattan(v->tile, dock->flat);
302 if (new_distance < best_distance) {
303 best_dock = dock;
304 best_distance = new_distance;
308 assert(best_dock != NULL);
310 return best_dock;
313 TileIndex Ship::GetOrderStationLocation(StationID station)
315 if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
317 const Station *st = Station::Get(station);
318 if (st->HasFacilities(FACIL_DOCK)) {
319 if (st->docks == NULL) {
320 return st->xy; // A buoy
321 } else {
322 const Dock* dock = GetBestDock(this, st);
324 DiagDirection direction = DiagdirBetweenTiles(dock->sloped, dock->flat);
325 return dock->flat + TileOffsByDiagDir(direction);
327 } else {
328 this->IncrementRealOrderIndex();
329 return 0;
333 void Ship::UpdateDeltaXY(Direction direction)
335 static const int8 _delta_xy_table[8][4] = {
336 /* y_extent, x_extent, y_offs, x_offs */
337 { 6, 6, -3, -3}, // N
338 { 6, 32, -3, -16}, // NE
339 { 6, 6, -3, -3}, // E
340 {32, 6, -16, -3}, // SE
341 { 6, 6, -3, -3}, // S
342 { 6, 32, -3, -16}, // SW
343 { 6, 6, -3, -3}, // W
344 {32, 6, -16, -3}, // NW
347 const int8 *bb = _delta_xy_table[direction];
348 this->x_offs = bb[3];
349 this->y_offs = bb[2];
350 this->x_extent = bb[1];
351 this->y_extent = bb[0];
352 this->z_extent = 6;
355 static bool CheckShipLeaveDepot(Ship *v)
357 if (!v->IsChainInDepot()) return false;
359 if (v->current_order.IsWaitTimetabled())
360 v->HandleWaiting(false);
361 if (v->current_order.IsType(OT_WAITING))
362 return true;
364 /* We are leaving a depot, but have to go to the exact same one; re-enter */
365 if (v->current_order.IsType(OT_GOTO_DEPOT) &&
366 IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
367 VehicleEnterDepot(v);
368 return true;
371 TileIndex tile = v->tile;
372 Axis axis = GetShipDepotAxis(tile);
374 DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
375 TileIndex north_neighbour = TILE_ADD(tile, TileOffsByDiagDir(north_dir));
376 DiagDirection south_dir = AxisToDiagDir(axis);
377 TileIndex south_neighbour = TILE_ADD(tile, 2 * TileOffsByDiagDir(south_dir));
379 TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
380 TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
381 if (north_tracks && south_tracks) {
382 /* Ask pathfinder for best direction */
383 bool reverse = false;
384 bool path_found;
385 switch (_settings_game.pf.pathfinder_for_ships) {
386 case VPF_OPF: reverse = OPFShipChooseTrack(v, north_neighbour, north_dir, north_tracks, path_found) == INVALID_TRACK; break; // OPF always allows reversing
387 case VPF_NPF: reverse = NPFShipCheckReverse(v); break;
388 case VPF_YAPF: reverse = YapfShipCheckReverse(v); break;
389 default: NOT_REACHED();
391 if (reverse) north_tracks = TRACK_BIT_NONE;
394 if (north_tracks) {
395 /* Leave towards north */
396 v->direction = DiagDirToDir(north_dir);
397 } else if (south_tracks) {
398 /* Leave towards south */
399 v->direction = DiagDirToDir(south_dir);
400 } else {
401 /* Both ways blocked */
402 return false;
405 v->state = AxisToTrackBits(axis);
406 v->vehstatus &= ~VS_HIDDEN;
408 v->cur_speed = 0;
409 v->UpdateViewport(true, true);
410 SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
412 PlayShipSound(v);
413 VehicleServiceInDepot(v);
414 InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
415 SetWindowClassesDirty(WC_SHIPS_LIST);
417 return false;
420 static bool ShipAccelerate(Vehicle *v)
422 uint spd;
423 byte t;
425 spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
426 spd = min(spd, v->current_order.GetMaxSpeed() * 2);
428 /* updates statusbar only if speed have changed to save CPU time */
429 if (spd != v->cur_speed) {
430 v->cur_speed = spd;
431 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
434 /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
435 spd = v->GetOldAdvanceSpeed(spd);
437 if (spd == 0) return false;
438 if ((byte)++spd == 0) return true;
440 v->progress = (t = v->progress) - (byte)spd;
442 return (t < v->progress);
446 * Ship arrives at a dock. If it is the first time, send out a news item.
447 * @param v Ship that arrived.
448 * @param st Station being visited.
450 static void ShipArrivesAt(const Vehicle *v, Station *st)
452 /* Check if station was ever visited before */
453 if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
454 st->had_vehicle_of_type |= HVOT_SHIP;
456 SetDParam(0, st->index);
457 AddVehicleNewsItem(
458 STR_NEWS_FIRST_SHIP_ARRIVAL,
459 (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
460 v->index,
461 st->index
463 AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
464 Game::NewEvent(new ScriptEventStationFirstVehicle(st->index, v->index));
470 * Runs the pathfinder to choose a track to continue along.
472 * @param v Ship to navigate
473 * @param tile Tile, the ship is about to enter
474 * @param enterdir Direction of entering
475 * @param tracks Available track choices on \a tile
476 * @return Track to choose, or INVALID_TRACK when to reverse.
478 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
480 assert(IsValidDiagDirection(enterdir));
482 bool path_found = true;
483 Track track;
484 switch (_settings_game.pf.pathfinder_for_ships) {
485 case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
486 case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
487 case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
488 default: NOT_REACHED();
491 v->HandlePathfindingResult(path_found);
492 return track;
495 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
497 return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
500 static const byte _ship_subcoord[4][6][3] = {
502 {15, 8, 1},
503 { 0, 0, 0},
504 { 0, 0, 0},
505 {15, 8, 2},
506 {15, 7, 0},
507 { 0, 0, 0},
510 { 0, 0, 0},
511 { 8, 0, 3},
512 { 7, 0, 2},
513 { 0, 0, 0},
514 { 8, 0, 4},
515 { 0, 0, 0},
518 { 0, 8, 5},
519 { 0, 0, 0},
520 { 0, 7, 6},
521 { 0, 0, 0},
522 { 0, 0, 0},
523 { 0, 8, 4},
526 { 0, 0, 0},
527 { 8, 15, 7},
528 { 0, 0, 0},
529 { 8, 15, 6},
530 { 0, 0, 0},
531 { 7, 15, 0},
535 /** Temporary data storage for testing collisions. */
536 struct ShipCollideChecker {
538 TrackBits track_bits; ///< Pathfinder chosen track converted to trackbits, or is v->state of requesting ship. (one bit set)
539 TileIndex tile; ///< Tile where ship was found, used to determine distance between ships.
542 /** Helper function for collision avoidance. */
543 static Vehicle *FindShipOnTile(Vehicle *v, void *data)
545 if (v->type != VEH_SHIP) return NULL;
547 ShipCollideChecker *scc = (ShipCollideChecker*)data;
549 /* Don't detect vehicles on different parallel tracks. */
550 TrackBits bits = scc->track_bits | Ship::From(v)->state;
551 if (bits == TRACK_BIT_HORZ || bits == TRACK_BIT_VERT) return NULL;
553 scc->tile = v->tile;
555 return v;
559 * If there is imminent collision or worse, direction and speed will be adjusted.
560 * @param tile Tile that the ship is about to enter.
561 * @param v Ship that does the request.
562 * @param tracks The available tracks that could be followed.
563 * @param track_old The track that the pathfinder assigned.
564 * @param diagdir The DiagDirection that tile will be entered.
565 * @return The new track if found.
567 static void CheckDistanceBetweenShips(TileIndex tile, Ship *v, TrackBits tracks, Track *track_old, DiagDirection diagdir)
569 if (DistanceManhattan(v->dest_tile, tile) <= 3 && !v->current_order.IsType(OT_GOTO_WAYPOINT)) return; // No checking close to docks and depots.
571 Track track = *track_old;
572 TrackBits track_bits = TrackToTrackBits(track);
574 /* Only check for collision when pathfinder did not change direction.
575 * This is done in order to keep ships moving towards the intended target. */
576 TrackBits combine = (v->state | track_bits);
577 if (combine != TRACK_BIT_HORZ && combine != TRACK_BIT_VERT && combine != track_bits) return;
579 TileIndex tile_plus_one = TileAddByDiagDir(tile, _ship_search_directions[track][diagdir]);
580 if (!IsValidTile(tile_plus_one)) tile_plus_one = tile;
581 TileIndex tile_plus_two = TileAddByDiagDir(tile_plus_one, diagdir);
582 if (!IsValidTile(tile_plus_two)) tile_plus_two = tile_plus_one;
584 ShipCollideChecker scc;
586 scc.track_bits = track_bits;
587 bool found = HasVehicleOnPos(tile, &scc, FindShipOnTile);
588 scc.track_bits = v->state;
589 if (!found) found = HasVehicleOnPos(tile_plus_one, &scc, FindShipOnTile);
590 scc.track_bits = track_bits;
591 if (!found) found = HasVehicleOnPos(tile_plus_two, &scc, FindShipOnTile);
593 if (found) {
595 /* Speed adjustment related to distance. */
596 v->cur_speed /= scc.tile == tile ? 8 : 2;
598 /* Clean none wanted trackbits, including pathfinder track and no 90 degree turns. */
599 tracks = IsDiagonalTrack(track) ? KillFirstBit(tracks) : (tracks & TRACK_BIT_CROSS);
601 /* Just follow track 1 tile and see if there is a track to follow. (try not to bang in coast or ship) */
602 while (tracks != TRACK_BIT_NONE) {
603 track = RemoveFirstTrack(&tracks);
605 TileIndex tile_check = TileAddByDiagDir(tile, _ship_search_directions[track][diagdir]);
606 if (!IsValidTile(tile_check)) continue;
608 if (HasVehicleOnPos(tile_check, &scc, &FindShipOnTile)) continue;
610 TrackBits bits = GetAvailShipTracks(tile_check, _ship_search_directions[track][diagdir]);
611 if (!IsDiagonalTrack(track)) bits &= TRACK_BIT_CROSS; // No 90 degree turns.
613 if (bits != INVALID_TRACK_BIT && bits != TRACK_BIT_NONE) {
614 *track_old = track;
615 break;
621 static void ShipController(Ship *v)
623 uint32 r;
624 const byte *b;
625 Direction dir;
626 Track track;
627 TrackBits tracks;
629 v->tick_counter++;
630 v->current_order_time++;
632 if (v->HandleBreakdown()) return;
634 if (v->vehstatus & VS_STOPPED) return;
636 ProcessOrders(v);
637 v->HandleLoading();
639 if (v->current_order.IsType(OT_LOADING)) return;
641 if (CheckShipLeaveDepot(v)) return;
643 v->ShowVisualEffect();
645 if (!ShipAccelerate(v)) return;
647 GetNewVehiclePosResult gp = GetNewVehiclePos(v);
648 if (v->state != TRACK_BIT_WORMHOLE) {
649 /* Not on a bridge */
650 if (gp.old_tile == gp.new_tile) {
651 /* Staying in tile */
652 if (v->IsInDepot()) {
653 gp.x = v->x_pos;
654 gp.y = v->y_pos;
655 } else {
656 /* Not inside depot */
657 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
658 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
660 /* A leave station order only needs one tick to get processed, so we can
661 * always skip ahead. */
662 if (v->current_order.IsType(OT_LEAVESTATION)) {
663 v->current_order.Free();
664 SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
665 } else if (v->dest_tile != 0) {
666 /* We have a target, let's see if we reached it... */
667 if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
668 DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
669 /* We got within 3 tiles of our target buoy, so let's skip to our
670 * next order */
671 UpdateVehicleTimetable(v, true);
672 v->IncrementRealOrderIndex();
673 v->current_order.MakeDummy();
674 } else {
675 /* Non-buoy orders really need to reach the tile */
676 if (v->dest_tile == gp.new_tile) {
677 if (v->current_order.IsType(OT_GOTO_DEPOT)) {
678 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
679 VehicleEnterDepot(v);
680 return;
682 } else if (v->current_order.IsType(OT_GOTO_STATION)) {
683 v->last_station_visited = v->current_order.GetDestination();
685 /* Process station in the orderlist. */
686 Station *st = Station::Get(v->current_order.GetDestination());
687 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
688 ShipArrivesAt(v, st);
689 v->BeginLoading();
690 } else { // leave stations without docks right aways
691 v->current_order.MakeLeaveStation();
692 v->IncrementRealOrderIndex();
699 } else {
700 /* New tile */
701 if (!IsValidTile(gp.new_tile)) goto reverse_direction;
703 DiagDirection diagdir = DiagdirBetweenTiles(gp.old_tile, gp.new_tile);
704 assert(diagdir != INVALID_DIAGDIR);
705 tracks = GetAvailShipTracks(gp.new_tile, diagdir);
706 if (tracks == TRACK_BIT_NONE) goto reverse_direction;
708 /* Choose a direction, and continue if we find one */
709 track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
710 if (track == INVALID_TRACK) goto reverse_direction;
712 /* Try to avoid collision and keep distance between ships. */
713 CheckDistanceBetweenShips(gp.new_tile, v, tracks, &track, diagdir);
715 b = _ship_subcoord[diagdir][track];
717 gp.x = (gp.x & ~0xF) | b[0];
718 gp.y = (gp.y & ~0xF) | b[1];
720 /* Call the landscape function and tell it that the vehicle entered the tile */
721 r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
722 if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
724 if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
725 v->tile = gp.new_tile;
726 v->state = TrackToTrackBits(track);
728 /* Update ship cache when the water class changes. Aqueducts are always canals. */
729 WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
730 WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
731 if (old_wc != new_wc) v->UpdateCache();
734 v->direction = (Direction)b[2];
736 } else {
737 /* On a bridge */
738 if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
739 v->x_pos = gp.x;
740 v->y_pos = gp.y;
741 v->UpdatePosition();
742 if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
743 return;
747 /* update image of ship, as well as delta XY */
748 v->x_pos = gp.x;
749 v->y_pos = gp.y;
750 v->z_pos = GetSlopePixelZ(gp.x, gp.y);
752 getout:
753 v->UpdatePosition();
754 v->UpdateViewport(true, true);
755 return;
757 reverse_direction:
758 dir = ReverseDir(v->direction);
759 v->direction = dir;
760 goto getout;
763 bool Ship::Tick()
765 if (!((this->vehstatus & VS_STOPPED) || this->IsChainInDepot())) this->running_ticks++;
767 ShipController(this);
769 return true;
773 * Build a ship.
774 * @param tile tile of the depot where ship is built.
775 * @param flags type of operation.
776 * @param e the engine to build.
777 * @param data unused.
778 * @param ret[out] the vehicle that has been built.
779 * @return the cost of this operation or an error.
781 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
783 tile = GetShipDepotNorthTile(tile);
784 if (flags & DC_EXEC) {
785 int x;
786 int y;
788 const ShipVehicleInfo *svi = &e->u.ship;
790 Ship *v = new Ship();
791 *ret = v;
793 v->owner = _current_company;
794 v->tile = tile;
795 x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
796 y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
797 v->x_pos = x;
798 v->y_pos = y;
799 v->z_pos = GetSlopePixelZ(x, y);
801 v->UpdateDeltaXY(v->direction);
802 v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
804 v->spritenum = svi->image_index;
805 v->cargo_type = e->GetDefaultCargoType();
806 v->cargo_cap = svi->capacity;
807 v->refit_cap = 0;
809 v->last_station_visited = INVALID_STATION;
810 v->last_loading_station = INVALID_STATION;
811 v->engine_type = e->index;
813 v->reliability = e->reliability;
814 v->reliability_spd_dec = e->reliability_spd_dec;
815 v->max_age = e->GetLifeLengthInDays();
816 _new_vehicle_id = v->index;
818 v->state = TRACK_BIT_DEPOT;
820 v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
821 v->date_of_last_service = _date;
822 v->build_year = _cur_year;
823 v->sprite_seq.Set(SPR_IMG_QUERY);
824 v->random_bits = VehicleRandomBits();
826 v->UpdateCache();
828 if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
829 v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
831 v->InvalidateNewGRFCacheOfChain();
833 v->cargo_cap = e->DetermineCapacity(v);
835 v->InvalidateNewGRFCacheOfChain();
837 v->UpdatePosition();
840 return CommandCost();
843 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
845 const Depot *depot = FindClosestShipDepot(this, 0);
847 if (depot == NULL) return false;
849 if (location != NULL) *location = depot->xy;
850 if (destination != NULL) *destination = depot->index;
852 return true;