ship_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: ship_cmd.cpp 24839 2012-12-23 01:00:25Z michi_cc $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "ship.h"
00014 #include "landscape.h"
00015 #include "timetable.h"
00016 #include "news_func.h"
00017 #include "company_func.h"
00018 #include "pathfinder/npf/npf_func.h"
00019 #include "depot_base.h"
00020 #include "station_base.h"
00021 #include "newgrf_engine.h"
00022 #include "pathfinder/yapf/yapf.h"
00023 #include "newgrf_sound.h"
00024 #include "spritecache.h"
00025 #include "strings_func.h"
00026 #include "window_func.h"
00027 #include "date_func.h"
00028 #include "vehicle_func.h"
00029 #include "sound_func.h"
00030 #include "ai/ai.hpp"
00031 #include "pathfinder/opf/opf_ship.h"
00032 #include "engine_base.h"
00033 #include "company_base.h"
00034 #include "tunnelbridge_map.h"
00035 #include "zoom_func.h"
00036 
00037 #include "table/strings.h"
00038 
00044 WaterClass GetEffectiveWaterClass(TileIndex tile)
00045 {
00046   if (HasTileWaterClass(tile)) return GetWaterClass(tile);
00047   if (IsTileType(tile, MP_TUNNELBRIDGE)) {
00048     assert(GetTunnelBridgeTransportType(tile) == TRANSPORT_WATER);
00049     return WATER_CLASS_CANAL;
00050   }
00051   if (IsTileType(tile, MP_RAILWAY)) {
00052     assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
00053     return WATER_CLASS_SEA;
00054   }
00055   NOT_REACHED();
00056 }
00057 
00058 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
00059 
00060 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
00061 {
00062   return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
00063 }
00064 
00065 static SpriteID GetShipIcon(EngineID engine, EngineImageType image_type)
00066 {
00067   const Engine *e = Engine::Get(engine);
00068   uint8 spritenum = e->u.ship.image_index;
00069 
00070   if (is_custom_sprite(spritenum)) {
00071     SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
00072     if (sprite != 0) return sprite;
00073 
00074     spritenum = e->original_image_index;
00075   }
00076 
00077   return DIR_W + _ship_sprites[spritenum];
00078 }
00079 
00080 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
00081 {
00082   SpriteID sprite = GetShipIcon(engine, image_type);
00083   const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
00084   preferred_x = Clamp(preferred_x, left - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI), right - UnScaleByZoom(real_sprite->width, ZOOM_LVL_GUI) - UnScaleByZoom(real_sprite->x_offs, ZOOM_LVL_GUI));
00085   DrawSprite(sprite, pal, preferred_x, y);
00086 }
00087 
00097 void GetShipSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
00098 {
00099   const Sprite *spr = GetSprite(GetShipIcon(engine, image_type), ST_NORMAL);
00100 
00101   width  = UnScaleByZoom(spr->width, ZOOM_LVL_GUI);
00102   height = UnScaleByZoom(spr->height, ZOOM_LVL_GUI);
00103   xoffs  = UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI);
00104   yoffs  = UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI);
00105 }
00106 
00107 SpriteID Ship::GetImage(Direction direction, EngineImageType image_type) const
00108 {
00109   uint8 spritenum = this->spritenum;
00110 
00111   if (is_custom_sprite(spritenum)) {
00112     SpriteID sprite = GetCustomVehicleSprite(this, direction, image_type);
00113     if (sprite != 0) return sprite;
00114 
00115     spritenum = this->GetEngine()->original_image_index;
00116   }
00117 
00118   return _ship_sprites[spritenum] + direction;
00119 }
00120 
00121 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
00122 {
00123   /* Find the closest depot */
00124   const Depot *depot;
00125   const Depot *best_depot = NULL;
00126   /* If we don't have a maximum distance, i.e. distance = 0,
00127    * we want to find any depot so the best distance of no
00128    * depot must be more than any correct distance. On the
00129    * other hand if we have set a maximum distance, any depot
00130    * further away than max_distance can safely be ignored. */
00131   uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
00132 
00133   FOR_ALL_DEPOTS(depot) {
00134     TileIndex tile = depot->xy;
00135     if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
00136       uint dist = DistanceManhattan(tile, v->tile);
00137       if (dist < best_dist) {
00138         best_dist = dist;
00139         best_depot = depot;
00140       }
00141     }
00142   }
00143 
00144   return best_depot;
00145 }
00146 
00147 static void CheckIfShipNeedsService(Vehicle *v)
00148 {
00149   if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
00150   if (v->IsChainInDepot()) {
00151     VehicleServiceInDepot(v);
00152     return;
00153   }
00154 
00155   uint max_distance;
00156   switch (_settings_game.pf.pathfinder_for_ships) {
00157     case VPF_OPF:  max_distance = 12; break;
00158     case VPF_NPF:  max_distance = _settings_game.pf.npf.maximum_go_to_depot_penalty  / NPF_TILE_LENGTH;  break;
00159     case VPF_YAPF: max_distance = _settings_game.pf.yapf.maximum_go_to_depot_penalty / YAPF_TILE_LENGTH; break;
00160     default: NOT_REACHED();
00161   }
00162 
00163   const Depot *depot = FindClosestShipDepot(v, max_distance);
00164 
00165   if (depot == NULL) {
00166     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00167       v->current_order.MakeDummy();
00168       SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00169     }
00170     return;
00171   }
00172 
00173   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
00174   v->dest_tile = depot->xy;
00175   SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00176 }
00177 
00181 void Ship::UpdateCache()
00182 {
00183   const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
00184 
00185   /* Get speed fraction for the current water type. Aqueducts are always canals. */
00186   bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
00187   uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
00188   this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
00189 
00190   /* Update cargo aging period. */
00191   this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
00192 
00193   this->UpdateVisualEffect();
00194 }
00195 
00196 Money Ship::GetRunningCost() const
00197 {
00198   const Engine *e = this->GetEngine();
00199   uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
00200   return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
00201 }
00202 
00203 void Ship::OnNewDay()
00204 {
00205   if ((++this->day_counter & 7) == 0) {
00206     DecreaseVehicleValue(this);
00207   }
00208 
00209   CheckVehicleBreakdown(this);
00210   AgeVehicle(this);
00211   CheckIfShipNeedsService(this);
00212 
00213   CheckOrders(this);
00214 
00215   if (this->running_ticks == 0) return;
00216 
00217   CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
00218 
00219   this->profit_this_year -= cost.GetCost();
00220   this->running_ticks = 0;
00221 
00222   SubtractMoneyFromCompanyFract(this->owner, cost);
00223 
00224   SetWindowDirty(WC_VEHICLE_DETAILS, this->index);
00225   /* we need this for the profit */
00226   SetWindowClassesDirty(WC_SHIPS_LIST);
00227 }
00228 
00229 Trackdir Ship::GetVehicleTrackdir() const
00230 {
00231   if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
00232 
00233   if (this->IsInDepot()) {
00234     /* We'll assume the ship is facing outwards */
00235     return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
00236   }
00237 
00238   if (this->state == TRACK_BIT_WORMHOLE) {
00239     /* ship on aqueduct, so just use his direction and assume a diagonal track */
00240     return DiagDirToDiagTrackdir(DirToDiagDir(this->direction));
00241   }
00242 
00243   return TrackDirectionToTrackdir(FindFirstTrack(this->state), this->direction);
00244 }
00245 
00246 void Ship::MarkDirty()
00247 {
00248   this->UpdateViewport(false, false);
00249   this->UpdateCache();
00250 }
00251 
00252 static void PlayShipSound(const Vehicle *v)
00253 {
00254   if (!PlayVehicleSound(v, VSE_START)) {
00255     SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
00256   }
00257 }
00258 
00259 void Ship::PlayLeaveStationSound() const
00260 {
00261   PlayShipSound(this);
00262 }
00263 
00264 TileIndex Ship::GetOrderStationLocation(StationID station)
00265 {
00266   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
00267 
00268   const Station *st = Station::Get(station);
00269   if (st->dock_tile != INVALID_TILE) {
00270     return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
00271   } else {
00272     this->IncrementRealOrderIndex();
00273     return 0;
00274   }
00275 }
00276 
00277 void Ship::UpdateDeltaXY(Direction direction)
00278 {
00279   static const int8 _delta_xy_table[8][4] = {
00280     /* y_extent, x_extent, y_offs, x_offs */
00281     { 6,  6,  -3,  -3}, // N
00282     { 6, 32,  -3, -16}, // NE
00283     { 6,  6,  -3,  -3}, // E
00284     {32,  6, -16,  -3}, // SE
00285     { 6,  6,  -3,  -3}, // S
00286     { 6, 32,  -3, -16}, // SW
00287     { 6,  6,  -3,  -3}, // W
00288     {32,  6, -16,  -3}, // NW
00289   };
00290 
00291   const int8 *bb = _delta_xy_table[direction];
00292   this->x_offs        = bb[3];
00293   this->y_offs        = bb[2];
00294   this->x_extent      = bb[1];
00295   this->y_extent      = bb[0];
00296   this->z_extent      = 6;
00297 }
00298 
00299 static const TileIndexDiffC _ship_leave_depot_offs[] = {
00300   {-1,  0},
00301   { 0, -1}
00302 };
00303 
00304 static bool CheckShipLeaveDepot(Ship *v)
00305 {
00306   if (!v->IsChainInDepot()) return false;
00307 
00308   /* We are leaving a depot, but have to go to the exact same one; re-enter */
00309   if (v->current_order.IsType(OT_GOTO_DEPOT) &&
00310       IsShipDepotTile(v->tile) && GetDepotIndex(v->tile) == v->current_order.GetDestination()) {
00311     VehicleEnterDepot(v);
00312     return true;
00313   }
00314 
00315   TileIndex tile = v->tile;
00316   Axis axis = GetShipDepotAxis(tile);
00317 
00318   DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
00319   TileIndex north_neighbour = TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis]));
00320   DiagDirection south_dir = AxisToDiagDir(axis);
00321   TileIndex south_neighbour = TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis]));
00322 
00323   TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
00324   TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
00325   if (north_tracks && south_tracks) {
00326     /* Ask pathfinder for best direction */
00327     bool reverse = false;
00328     bool path_found;
00329     switch (_settings_game.pf.pathfinder_for_ships) {
00330       case VPF_OPF: reverse = OPFShipChooseTrack(v, north_neighbour, north_dir, north_tracks, path_found) == INVALID_TRACK; break; // OPF always allows reversing
00331       case VPF_NPF: reverse = NPFShipCheckReverse(v); break;
00332       case VPF_YAPF: reverse = YapfShipCheckReverse(v); break;
00333       default: NOT_REACHED();
00334     }
00335     if (reverse) north_tracks = TRACK_BIT_NONE;
00336   }
00337 
00338   if (north_tracks) {
00339     /* Leave towards north */
00340     v->direction = DiagDirToDir(north_dir);
00341   } else if (south_tracks) {
00342     /* Leave towards south */
00343     v->direction = DiagDirToDir(south_dir);
00344   } else {
00345     /* Both ways blocked */
00346     return false;
00347   }
00348 
00349   v->state = AxisToTrackBits(axis);
00350   v->vehstatus &= ~VS_HIDDEN;
00351 
00352   v->cur_speed = 0;
00353   v->UpdateViewport(true, true);
00354   SetWindowDirty(WC_VEHICLE_DEPOT, v->tile);
00355 
00356   PlayShipSound(v);
00357   VehicleServiceInDepot(v);
00358   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00359   SetWindowClassesDirty(WC_SHIPS_LIST);
00360 
00361   return false;
00362 }
00363 
00364 static bool ShipAccelerate(Vehicle *v)
00365 {
00366   uint spd;
00367   byte t;
00368 
00369   spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
00370   spd = min(spd, v->current_order.max_speed * 2);
00371 
00372   /* updates statusbar only if speed have changed to save CPU time */
00373   if (spd != v->cur_speed) {
00374     v->cur_speed = spd;
00375     SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00376   }
00377 
00378   /* Convert direction-indepenent speed into direction-dependent speed. (old movement method) */
00379   spd = v->GetOldAdvanceSpeed(spd);
00380 
00381   if (spd == 0) return false;
00382   if ((byte)++spd == 0) return true;
00383 
00384   v->progress = (t = v->progress) - (byte)spd;
00385 
00386   return (t < v->progress);
00387 }
00388 
00394 static void ShipArrivesAt(const Vehicle *v, Station *st)
00395 {
00396   /* Check if station was ever visited before */
00397   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
00398     st->had_vehicle_of_type |= HVOT_SHIP;
00399 
00400     SetDParam(0, st->index);
00401     AddVehicleNewsItem(
00402       STR_NEWS_FIRST_SHIP_ARRIVAL,
00403       (v->owner == _local_company) ? NT_ARRIVAL_COMPANY : NT_ARRIVAL_OTHER,
00404       v->index,
00405       st->index
00406     );
00407     AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
00408   }
00409 }
00410 
00411 
00421 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
00422 {
00423   assert(IsValidDiagDirection(enterdir));
00424 
00425   bool path_found = true;
00426   Track track;
00427   switch (_settings_game.pf.pathfinder_for_ships) {
00428     case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00429     case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00430     case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
00431     default: NOT_REACHED();
00432   }
00433 
00434   v->HandlePathfindingResult(path_found);
00435   return track;
00436 }
00437 
00438 static const Direction _new_vehicle_direction_table[] = {
00439   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
00440   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
00441   DIR_E , DIR_SE, DIR_S
00442 };
00443 
00444 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
00445 {
00446   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
00447               TileX(new_tile) - TileX(old_tile) + 1;
00448   assert(offs < 11 && offs != 3 && offs != 7);
00449   return _new_vehicle_direction_table[offs];
00450 }
00451 
00452 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
00453 {
00454   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
00455   assert(offs < 11 && offs != 3 && offs != 7);
00456   return _new_vehicle_direction_table[offs];
00457 }
00458 
00459 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
00460 {
00461   return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
00462 }
00463 
00464 static const byte _ship_subcoord[4][6][3] = {
00465   {
00466     {15, 8, 1},
00467     { 0, 0, 0},
00468     { 0, 0, 0},
00469     {15, 8, 2},
00470     {15, 7, 0},
00471     { 0, 0, 0},
00472   },
00473   {
00474     { 0, 0, 0},
00475     { 8, 0, 3},
00476     { 7, 0, 2},
00477     { 0, 0, 0},
00478     { 8, 0, 4},
00479     { 0, 0, 0},
00480   },
00481   {
00482     { 0, 8, 5},
00483     { 0, 0, 0},
00484     { 0, 7, 6},
00485     { 0, 0, 0},
00486     { 0, 0, 0},
00487     { 0, 8, 4},
00488   },
00489   {
00490     { 0, 0, 0},
00491     { 8, 15, 7},
00492     { 0, 0, 0},
00493     { 8, 15, 6},
00494     { 0, 0, 0},
00495     { 7, 15, 0},
00496   }
00497 };
00498 
00499 static void ShipController(Ship *v)
00500 {
00501   uint32 r;
00502   const byte *b;
00503   Direction dir;
00504   Track track;
00505   TrackBits tracks;
00506 
00507   v->tick_counter++;
00508   v->current_order_time++;
00509 
00510   if (v->HandleBreakdown()) return;
00511 
00512   if (v->vehstatus & VS_STOPPED) return;
00513 
00514   ProcessOrders(v);
00515   v->HandleLoading();
00516 
00517   if (v->current_order.IsType(OT_LOADING)) return;
00518 
00519   if (CheckShipLeaveDepot(v)) return;
00520 
00521   v->ShowVisualEffect();
00522 
00523   if (!ShipAccelerate(v)) return;
00524 
00525   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
00526   if (v->state != TRACK_BIT_WORMHOLE) {
00527     /* Not on a bridge */
00528     if (gp.old_tile == gp.new_tile) {
00529       /* Staying in tile */
00530       if (v->IsInDepot()) {
00531         gp.x = v->x_pos;
00532         gp.y = v->y_pos;
00533       } else {
00534         /* Not inside depot */
00535         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00536         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00537 
00538         /* A leave station order only needs one tick to get processed, so we can
00539          * always skip ahead. */
00540         if (v->current_order.IsType(OT_LEAVESTATION)) {
00541           v->current_order.Free();
00542           SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP);
00543         } else if (v->dest_tile != 0) {
00544           /* We have a target, let's see if we reached it... */
00545           if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
00546               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
00547             /* We got within 3 tiles of our target buoy, so let's skip to our
00548              * next order */
00549             UpdateVehicleTimetable(v, true);
00550             v->IncrementRealOrderIndex();
00551             v->current_order.MakeDummy();
00552           } else {
00553             /* Non-buoy orders really need to reach the tile */
00554             if (v->dest_tile == gp.new_tile) {
00555               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00556                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
00557                   VehicleEnterDepot(v);
00558                   return;
00559                 }
00560               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
00561                 v->last_station_visited = v->current_order.GetDestination();
00562 
00563                 /* Process station in the orderlist. */
00564                 Station *st = Station::Get(v->current_order.GetDestination());
00565                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
00566                   ShipArrivesAt(v, st);
00567                   v->BeginLoading();
00568                 } else { // leave stations without docks right aways
00569                   v->current_order.MakeLeaveStation();
00570                   v->IncrementRealOrderIndex();
00571                 }
00572               }
00573             }
00574           }
00575         }
00576       }
00577     } else {
00578       /* New tile */
00579       if (!IsValidTile(gp.new_tile)) goto reverse_direction;
00580 
00581       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
00582       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
00583       DiagDirection diagdir = DirToDiagDir(dir);
00584       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
00585       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
00586 
00587       /* Choose a direction, and continue if we find one */
00588       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
00589       if (track == INVALID_TRACK) goto reverse_direction;
00590 
00591       b = _ship_subcoord[diagdir][track];
00592 
00593       gp.x = (gp.x & ~0xF) | b[0];
00594       gp.y = (gp.y & ~0xF) | b[1];
00595 
00596       /* Call the landscape function and tell it that the vehicle entered the tile */
00597       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00598       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00599 
00600       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
00601         v->tile = gp.new_tile;
00602         v->state = TrackToTrackBits(track);
00603 
00604         /* Update ship cache when the water class changes. Aqueducts are always canals. */
00605         WaterClass old_wc = GetEffectiveWaterClass(gp.old_tile);
00606         WaterClass new_wc = GetEffectiveWaterClass(gp.new_tile);
00607         if (old_wc != new_wc) v->UpdateCache();
00608       }
00609 
00610       v->direction = (Direction)b[2];
00611     }
00612   } else {
00613     /* On a bridge */
00614     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
00615       v->x_pos = gp.x;
00616       v->y_pos = gp.y;
00617       VehicleUpdatePosition(v);
00618       if ((v->vehstatus & VS_HIDDEN) == 0) VehicleUpdateViewport(v, true);
00619       return;
00620     }
00621   }
00622 
00623   /* update image of ship, as well as delta XY */
00624   dir = ShipGetNewDirection(v, gp.x, gp.y);
00625   v->x_pos = gp.x;
00626   v->y_pos = gp.y;
00627   v->z_pos = GetSlopePixelZ(gp.x, gp.y);
00628 
00629 getout:
00630   VehicleUpdatePosition(v);
00631   v->UpdateViewport(true, true);
00632   return;
00633 
00634 reverse_direction:
00635   dir = ReverseDir(v->direction);
00636   v->direction = dir;
00637   goto getout;
00638 }
00639 
00640 bool Ship::Tick()
00641 {
00642   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
00643 
00644   ShipController(this);
00645 
00646   return true;
00647 }
00648 
00658 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
00659 {
00660   tile = GetShipDepotNorthTile(tile);
00661   if (flags & DC_EXEC) {
00662     int x;
00663     int y;
00664 
00665     const ShipVehicleInfo *svi = &e->u.ship;
00666 
00667     Ship *v = new Ship();
00668     *ret = v;
00669 
00670     v->owner = _current_company;
00671     v->tile = tile;
00672     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
00673     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
00674     v->x_pos = x;
00675     v->y_pos = y;
00676     v->z_pos = GetSlopePixelZ(x, y);
00677 
00678     v->UpdateDeltaXY(v->direction);
00679     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00680 
00681     v->spritenum = svi->image_index;
00682     v->cargo_type = e->GetDefaultCargoType();
00683     v->cargo_cap = svi->capacity;
00684 
00685     v->last_station_visited = INVALID_STATION;
00686     v->engine_type = e->index;
00687 
00688     v->reliability = e->reliability;
00689     v->reliability_spd_dec = e->reliability_spd_dec;
00690     v->max_age = e->GetLifeLengthInDays();
00691     _new_vehicle_id = v->index;
00692 
00693     v->state = TRACK_BIT_DEPOT;
00694 
00695     v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_ships;
00696     v->date_of_last_service = _date;
00697     v->build_year = _cur_year;
00698     v->cur_image = SPR_IMG_QUERY;
00699     v->random_bits = VehicleRandomBits();
00700 
00701     v->UpdateCache();
00702 
00703     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00704 
00705     v->InvalidateNewGRFCacheOfChain();
00706 
00707     v->cargo_cap = e->DetermineCapacity(v);
00708 
00709     v->InvalidateNewGRFCacheOfChain();
00710 
00711     VehicleUpdatePosition(v);
00712   }
00713 
00714   return CommandCost();
00715 }
00716 
00717 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
00718 {
00719   const Depot *depot = FindClosestShipDepot(this, 0);
00720 
00721   if (depot == NULL) return false;
00722 
00723   if (location    != NULL) *location    = depot->xy;
00724   if (destination != NULL) *destination = depot->index;
00725 
00726   return true;
00727 }