ship_cmd.cpp

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