ship_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: ship_cmd.cpp 15434 2009-02-09 21:20:05Z rubidium $ */
00002 
00005 #include "stdafx.h"
00006 #include "ship.h"
00007 #include "landscape.h"
00008 #include "timetable.h"
00009 #include "command_func.h"
00010 #include "pathfind.h"
00011 #include "station_map.h"
00012 #include "news_func.h"
00013 #include "company_func.h"
00014 #include "npf.h"
00015 #include "depot_base.h"
00016 #include "vehicle_gui.h"
00017 #include "newgrf_engine.h"
00018 #include "yapf/yapf.h"
00019 #include "newgrf_sound.h"
00020 #include "spritecache.h"
00021 #include "strings_func.h"
00022 #include "functions.h"
00023 #include "window_func.h"
00024 #include "date_func.h"
00025 #include "vehicle_func.h"
00026 #include "sound_func.h"
00027 #include "variables.h"
00028 #include "autoreplace_gui.h"
00029 #include "gfx_func.h"
00030 #include "effectvehicle_func.h"
00031 #include "settings_type.h"
00032 #include "ai/ai.hpp"
00033 
00034 #include "table/strings.h"
00035 #include "table/sprites.h"
00036 
00037 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
00038 
00039 static const TrackBits _ship_sometracks[4] = {
00040   TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT,  // 0x19, // DIAGDIR_NE
00041   TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT,  // 0x16, // DIAGDIR_SE
00042   TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT, // 0x25, // DIAGDIR_SW
00043   TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_RIGHT, // 0x2A, // DIAGDIR_NW
00044 };
00045 
00046 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
00047 {
00048   return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
00049 }
00050 
00051 static SpriteID GetShipIcon(EngineID engine)
00052 {
00053   uint8 spritenum = ShipVehInfo(engine)->image_index;
00054 
00055   if (is_custom_sprite(spritenum)) {
00056     SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
00057     if (sprite != 0) return sprite;
00058 
00059     spritenum = GetEngine(engine)->image_index;
00060   }
00061 
00062   return 6 + _ship_sprites[spritenum];
00063 }
00064 
00065 void DrawShipEngine(int x, int y, EngineID engine, SpriteID pal)
00066 {
00067   DrawSprite(GetShipIcon(engine), pal, x, y);
00068 }
00069 
00075 void GetShipSpriteSize(EngineID engine, uint &width, uint &height)
00076 {
00077   const Sprite *spr = GetSprite(GetShipIcon(engine), ST_NORMAL);
00078 
00079   width  = spr->width;
00080   height = spr->height;
00081 }
00082 
00083 SpriteID Ship::GetImage(Direction direction) const
00084 {
00085   uint8 spritenum = this->spritenum;
00086 
00087   if (is_custom_sprite(spritenum)) {
00088     SpriteID sprite = GetCustomVehicleSprite(this, direction);
00089     if (sprite != 0) return sprite;
00090 
00091     spritenum = GetEngine(this->engine_type)->image_index;
00092   }
00093 
00094   return _ship_sprites[spritenum] + direction;
00095 }
00096 
00097 static const Depot *FindClosestShipDepot(const Vehicle *v)
00098 {
00099   if (_settings_game.pf.pathfinder_for_ships == VPF_NPF) { /* NPF is used */
00100     Trackdir trackdir = GetVehicleTrackdir(v);
00101     NPFFoundTargetData ftd = NPFRouteToDepotTrialError(v->tile, trackdir, false, TRANSPORT_WATER, 0, v->owner, INVALID_RAILTYPES);
00102 
00103     if (ftd.best_bird_dist == 0) return GetDepotByTile(ftd.node.tile); /* Found target */
00104 
00105     return NULL; /* Did not find target */
00106   }
00107 
00108   /* OPF or YAPF - find the closest depot */
00109 
00110   const Depot *depot;
00111   const Depot *best_depot = NULL;
00112   uint best_dist = UINT_MAX;
00113 
00114   FOR_ALL_DEPOTS(depot) {
00115     TileIndex tile = depot->xy;
00116     if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
00117       uint dist = DistanceManhattan(tile, v->tile);
00118       if (dist < best_dist) {
00119         best_dist = dist;
00120         best_depot = depot;
00121       }
00122     }
00123   }
00124 
00125   return best_depot;
00126 }
00127 
00128 static void CheckIfShipNeedsService(Vehicle *v)
00129 {
00130   if (_settings_game.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
00131   if (v->IsInDepot()) {
00132     VehicleServiceInDepot(v);
00133     return;
00134   }
00135 
00136   const Depot *depot = FindClosestShipDepot(v);
00137 
00138   if (depot == NULL || DistanceManhattan(v->tile, depot->xy) > 12) {
00139     if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00140       v->current_order.MakeDummy();
00141       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00142     }
00143     return;
00144   }
00145 
00146   v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
00147   v->dest_tile = depot->xy;
00148   InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00149 }
00150 
00151 Money Ship::GetRunningCost() const
00152 {
00153   return GetVehicleProperty(this, 0x0F, ShipVehInfo(this->engine_type)->running_cost) * _price.ship_running;
00154 }
00155 
00156 void Ship::OnNewDay()
00157 {
00158   if ((++this->day_counter & 7) == 0)
00159     DecreaseVehicleValue(this);
00160 
00161   CheckVehicleBreakdown(this);
00162   AgeVehicle(this);
00163   CheckIfShipNeedsService(this);
00164 
00165   CheckOrders(this);
00166 
00167   if (this->running_ticks == 0) return;
00168 
00169   CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
00170 
00171   this->profit_this_year -= cost.GetCost();
00172   this->running_ticks = 0;
00173 
00174   SubtractMoneyFromCompanyFract(this->owner, cost);
00175 
00176   InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
00177   /* we need this for the profit */
00178   InvalidateWindowClasses(WC_SHIPS_LIST);
00179 }
00180 
00181 static void HandleBrokenShip(Vehicle *v)
00182 {
00183   if (v->breakdown_ctr != 1) {
00184     v->breakdown_ctr = 1;
00185     v->cur_speed = 0;
00186 
00187     if (v->breakdowns_since_last_service != 255)
00188       v->breakdowns_since_last_service++;
00189 
00190     InvalidateWindow(WC_VEHICLE_VIEW, v->index);
00191     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00192 
00193     if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
00194       SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
00195         SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
00196     }
00197 
00198     if (!(v->vehstatus & VS_HIDDEN)) {
00199       Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
00200       if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
00201     }
00202   }
00203 
00204   if (!(v->tick_counter & 1)) {
00205     if (!--v->breakdown_delay) {
00206       v->breakdown_ctr = 0;
00207       InvalidateWindow(WC_VEHICLE_VIEW, v->index);
00208     }
00209   }
00210 }
00211 
00212 void Ship::MarkDirty()
00213 {
00214   this->cur_image = this->GetImage(this->direction);
00215   MarkSingleVehicleDirty(this);
00216 }
00217 
00218 static void PlayShipSound(const Vehicle *v)
00219 {
00220   if (!PlayVehicleSound(v, VSE_START)) {
00221     SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
00222   }
00223 }
00224 
00225 void Ship::PlayLeaveStationSound() const
00226 {
00227   PlayShipSound(this);
00228 }
00229 
00230 TileIndex Ship::GetOrderStationLocation(StationID station)
00231 {
00232   if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
00233 
00234   const Station *st = GetStation(station);
00235   if (st->dock_tile != INVALID_TILE) {
00236     return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
00237   } else {
00238     this->cur_order_index++;
00239     return 0;
00240   }
00241 }
00242 
00243 void Ship::UpdateDeltaXY(Direction direction)
00244 {
00245 #define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
00246   static const uint32 _delta_xy_table[8] = {
00247     MKIT( 6,  6,  -3,  -3),
00248     MKIT( 6, 32,  -3, -16),
00249     MKIT( 6,  6,  -3,  -3),
00250     MKIT(32,  6, -16,  -3),
00251     MKIT( 6,  6,  -3,  -3),
00252     MKIT( 6, 32,  -3, -16),
00253     MKIT( 6,  6,  -3,  -3),
00254     MKIT(32,  6, -16,  -3),
00255   };
00256 #undef MKIT
00257 
00258   uint32 x = _delta_xy_table[direction];
00259   this->x_offs        = GB(x,  0, 8);
00260   this->y_offs        = GB(x,  8, 8);
00261   this->x_extent      = GB(x, 16, 8);
00262   this->y_extent      = GB(x, 24, 8);
00263   this->z_extent      = 6;
00264 }
00265 
00266 void RecalcShipStuff(Vehicle *v)
00267 {
00268   v->UpdateDeltaXY(v->direction);
00269   v->cur_image = v->GetImage(v->direction);
00270   v->MarkDirty();
00271   InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
00272 }
00273 
00274 static const TileIndexDiffC _ship_leave_depot_offs[] = {
00275   {-1,  0},
00276   { 0, -1}
00277 };
00278 
00279 static void CheckShipLeaveDepot(Vehicle *v)
00280 {
00281   if (!v->IsInDepot()) return;
00282 
00283   TileIndex tile = v->tile;
00284   Axis axis = GetShipDepotAxis(tile);
00285 
00286   /* Check first (north) side */
00287   if (_ship_sometracks[axis] & GetTileShipTrackStatus(TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00288     v->direction = ReverseDir(AxisToDirection(axis));
00289   /* Check second (south) side */
00290   } else if (_ship_sometracks[axis + 2] & GetTileShipTrackStatus(TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
00291     v->direction = AxisToDirection(axis);
00292   } else {
00293     return;
00294   }
00295 
00296   v->u.ship.state = AxisToTrackBits(axis);
00297   v->vehstatus &= ~VS_HIDDEN;
00298 
00299   v->cur_speed = 0;
00300   RecalcShipStuff(v);
00301 
00302   PlayShipSound(v);
00303   VehicleServiceInDepot(v);
00304   InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00305   InvalidateWindowClasses(WC_SHIPS_LIST);
00306 }
00307 
00308 static bool ShipAccelerate(Vehicle *v)
00309 {
00310   uint spd;
00311   byte t;
00312 
00313   spd = min(v->cur_speed + 1, GetVehicleProperty(v, 0x0B, v->max_speed));
00314 
00315   /*updates statusbar only if speed have changed to save CPU time */
00316   if (spd != v->cur_speed) {
00317     v->cur_speed = spd;
00318     if (_settings_client.gui.vehicle_speed)
00319       InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00320   }
00321 
00322   /* Decrease somewhat when turning */
00323   if (!(v->direction & 1)) spd = spd * 3 / 4;
00324 
00325   if (spd == 0) return false;
00326   if ((byte)++spd == 0) return true;
00327 
00328   v->progress = (t = v->progress) - (byte)spd;
00329 
00330   return (t < v->progress);
00331 }
00332 
00333 static void ShipArrivesAt(const Vehicle *v, Station *st)
00334 {
00335   /* Check if station was ever visited before */
00336   if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
00337     st->had_vehicle_of_type |= HVOT_SHIP;
00338 
00339     SetDParam(0, st->index);
00340     AddNewsItem(
00341       STR_9833_CITIZENS_CELEBRATE_FIRST,
00342       (v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
00343       v->index,
00344       st->index
00345     );
00346     AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
00347   }
00348 }
00349 
00350 struct PathFindShip {
00351   TileIndex skiptile;
00352   TileIndex dest_coords;
00353   uint best_bird_dist;
00354   uint best_length;
00355 };
00356 
00357 static bool ShipTrackFollower(TileIndex tile, PathFindShip *pfs, int track, uint length)
00358 {
00359   /* Found dest? */
00360   if (tile == pfs->dest_coords) {
00361     pfs->best_bird_dist = 0;
00362 
00363     pfs->best_length = minu(pfs->best_length, length);
00364     return true;
00365   }
00366 
00367   /* Skip this tile in the calculation */
00368   if (tile != pfs->skiptile) {
00369     pfs->best_bird_dist = minu(pfs->best_bird_dist, DistanceMaxPlusManhattan(pfs->dest_coords, tile));
00370   }
00371 
00372   return false;
00373 }
00374 
00375 static const byte _ship_search_directions[6][4] = {
00376   { 0, 9, 2, 9 },
00377   { 9, 1, 9, 3 },
00378   { 9, 0, 3, 9 },
00379   { 1, 9, 9, 2 },
00380   { 3, 2, 9, 9 },
00381   { 9, 9, 1, 0 },
00382 };
00383 
00384 static const byte _pick_shiptrack_table[6] = {1, 3, 2, 2, 0, 0};
00385 
00386 static uint FindShipTrack(Vehicle *v, TileIndex tile, DiagDirection dir, TrackBits bits, TileIndex skiptile, Track *track)
00387 {
00388   PathFindShip pfs;
00389   Track i, best_track;
00390   uint best_bird_dist = 0;
00391   uint best_length    = 0;
00392   uint r;
00393   byte ship_dir = v->direction & 3;
00394 
00395   pfs.dest_coords = v->dest_tile;
00396   pfs.skiptile = skiptile;
00397 
00398   best_track = INVALID_TRACK;
00399 
00400   do {
00401     i = RemoveFirstTrack(&bits);
00402 
00403     pfs.best_bird_dist = UINT_MAX;
00404     pfs.best_length = UINT_MAX;
00405 
00406     FollowTrack(tile, PATHFIND_FLAGS_SHIP_MODE | PATHFIND_FLAGS_DISABLE_TILE_HASH, TRANSPORT_WATER, 0, (DiagDirection)_ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs);
00407 
00408     if (best_track != INVALID_TRACK) {
00409       if (pfs.best_bird_dist != 0) {
00410         /* neither reached the destination, pick the one with the smallest bird dist */
00411         if (pfs.best_bird_dist > best_bird_dist) goto bad;
00412         if (pfs.best_bird_dist < best_bird_dist) goto good;
00413       } else {
00414         if (pfs.best_length > best_length) goto bad;
00415         if (pfs.best_length < best_length) goto good;
00416       }
00417 
00418       /* if we reach this position, there's two paths of equal value so far.
00419        * pick one randomly. */
00420       r = GB(Random(), 0, 8);
00421       if (_pick_shiptrack_table[i] == ship_dir) r += 80;
00422       if (_pick_shiptrack_table[best_track] == ship_dir) r -= 80;
00423       if (r <= 127) goto bad;
00424     }
00425 good:;
00426     best_track = i;
00427     best_bird_dist = pfs.best_bird_dist;
00428     best_length = pfs.best_length;
00429 bad:;
00430 
00431   } while (bits != 0);
00432 
00433   *track = best_track;
00434   return best_bird_dist;
00435 }
00436 
00437 static inline NPFFoundTargetData PerfNPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, TransportType type, Owner owner, RailTypes railtypes)
00438 {
00439 
00440   void *perf = NpfBeginInterval();
00441   NPFFoundTargetData ret = NPFRouteToStationOrTile(tile, trackdir, ignore_start_tile, target, type, 0, owner, railtypes);
00442   int t = NpfEndInterval(perf);
00443   DEBUG(yapf, 4, "[NPFW] %d us - %d rounds - %d open - %d closed -- ", t, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
00444   return ret;
00445 }
00446 
00450 static Track ChooseShipTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
00451 {
00452   assert(IsValidDiagDirection(enterdir));
00453 
00454   switch (_settings_game.pf.pathfinder_for_ships) {
00455     case VPF_YAPF: { /* YAPF */
00456       Trackdir trackdir = YapfChooseShipTrack(v, tile, enterdir, tracks);
00457       if (trackdir != INVALID_TRACKDIR) return TrackdirToTrack(trackdir);
00458     } break;
00459 
00460     case VPF_NPF: { /* NPF */
00461       NPFFindStationOrTileData fstd;
00462       Trackdir trackdir = GetVehicleTrackdir(v);
00463       assert(trackdir != INVALID_TRACKDIR); // Check that we are not in a depot
00464 
00465       NPFFillWithOrderData(&fstd, v);
00466 
00467       NPFFoundTargetData ftd = PerfNPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, TRANSPORT_WATER, v->owner, INVALID_RAILTYPES);
00468 
00469       /* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
00470        * the direction we need to take to get there, if ftd.best_bird_dist is not 0,
00471        * we did not find our target, but ftd.best_trackdir contains the direction leading
00472        * to the tile closest to our target. */
00473       if (ftd.best_trackdir != 0xff) return TrackdirToTrack(ftd.best_trackdir); /* TODO: Wrapper function? */
00474     } break;
00475 
00476     default:
00477     case VPF_OPF: { /* OPF */
00478       TileIndex tile2 = TILE_ADD(tile, -TileOffsByDiagDir(enterdir));
00479       Track track;
00480 
00481       /* Let's find out how far it would be if we would reverse first */
00482       TrackBits b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state;
00483 
00484       uint distr = UINT_MAX; // distance if we reversed
00485       if (b != 0) {
00486         distr = FindShipTrack(v, tile2, ReverseDiagDir(enterdir), b, tile, &track);
00487         if (distr != UINT_MAX) distr++; // penalty for reversing
00488       }
00489 
00490       /* And if we would not reverse? */
00491       uint dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track);
00492 
00493       if (dist <= distr) return track;
00494     } break;
00495   }
00496 
00497   return INVALID_TRACK; /* We could better reverse */
00498 }
00499 
00500 static const Direction _new_vehicle_direction_table[] = {
00501   DIR_N , DIR_NW, DIR_W , INVALID_DIR,
00502   DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
00503   DIR_E , DIR_SE, DIR_S
00504 };
00505 
00506 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
00507 {
00508   uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
00509               TileX(new_tile) - TileX(old_tile) + 1;
00510   assert(offs < 11 && offs != 3 && offs != 7);
00511   return _new_vehicle_direction_table[offs];
00512 }
00513 
00514 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
00515 {
00516   uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
00517   assert(offs < 11 && offs != 3 && offs != 7);
00518   return _new_vehicle_direction_table[offs];
00519 }
00520 
00521 static inline TrackBits GetAvailShipTracks(TileIndex tile, int dir)
00522 {
00523   return GetTileShipTrackStatus(tile) & _ship_sometracks[dir];
00524 }
00525 
00526 static const byte _ship_subcoord[4][6][3] = {
00527   {
00528     {15, 8, 1},
00529     { 0, 0, 0},
00530     { 0, 0, 0},
00531     {15, 8, 2},
00532     {15, 7, 0},
00533     { 0, 0, 0},
00534   },
00535   {
00536     { 0, 0, 0},
00537     { 8, 0, 3},
00538     { 7, 0, 2},
00539     { 0, 0, 0},
00540     { 8, 0, 4},
00541     { 0, 0, 0},
00542   },
00543   {
00544     { 0, 8, 5},
00545     { 0, 0, 0},
00546     { 0, 7, 6},
00547     { 0, 0, 0},
00548     { 0, 0, 0},
00549     { 0, 8, 4},
00550   },
00551   {
00552     { 0, 0, 0},
00553     { 8, 15, 7},
00554     { 0, 0, 0},
00555     { 8, 15, 6},
00556     { 0, 0, 0},
00557     { 7, 15, 0},
00558   }
00559 };
00560 
00561 static void ShipController(Vehicle *v)
00562 {
00563   uint32 r;
00564   const byte *b;
00565   Direction dir;
00566   Track track;
00567   TrackBits tracks;
00568 
00569   v->tick_counter++;
00570   v->current_order_time++;
00571 
00572   if (v->breakdown_ctr != 0) {
00573     if (v->breakdown_ctr <= 2) {
00574       HandleBrokenShip(v);
00575       return;
00576     }
00577     if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
00578   }
00579 
00580   if (v->vehstatus & VS_STOPPED) return;
00581 
00582   ProcessOrders(v);
00583   v->HandleLoading();
00584 
00585   if (v->current_order.IsType(OT_LOADING)) return;
00586 
00587   CheckShipLeaveDepot(v);
00588 
00589   if (!ShipAccelerate(v)) return;
00590 
00591   BeginVehicleMove(v);
00592 
00593   GetNewVehiclePosResult gp = GetNewVehiclePos(v);
00594   if (v->u.ship.state != TRACK_BIT_WORMHOLE) {
00595     /* Not on a bridge */
00596     if (gp.old_tile == gp.new_tile) {
00597       /* Staying in tile */
00598       if (v->IsInDepot()) {
00599         gp.x = v->x_pos;
00600         gp.y = v->y_pos;
00601       } else {
00602         /* Not inside depot */
00603         r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00604         if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00605 
00606         /* A leave station order only needs one tick to get processed, so we can
00607         * always skip ahead. */
00608         if (v->current_order.IsType(OT_LEAVESTATION)) {
00609           v->current_order.Free();
00610           InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
00611         } else if (v->dest_tile != 0) {
00612           /* We have a target, let's see if we reached it... */
00613           if (v->current_order.IsType(OT_GOTO_STATION) &&
00614               IsBuoyTile(v->dest_tile) &&
00615               DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
00616             /* We got within 3 tiles of our target buoy, so let's skip to our
00617             * next order */
00618             UpdateVehicleTimetable(v, true);
00619             v->cur_order_index++;
00620             v->current_order.MakeDummy();
00621             InvalidateVehicleOrder(v, 0);
00622           } else {
00623             /* Non-buoy orders really need to reach the tile */
00624             if (v->dest_tile == gp.new_tile) {
00625               if (v->current_order.IsType(OT_GOTO_DEPOT)) {
00626                 if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
00627                   VehicleEnterDepot(v);
00628                   return;
00629                 }
00630               } else if (v->current_order.IsType(OT_GOTO_STATION)) {
00631                 v->last_station_visited = v->current_order.GetDestination();
00632 
00633                 /* Process station in the orderlist. */
00634                 Station *st = GetStation(v->current_order.GetDestination());
00635                 if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
00636                   ShipArrivesAt(v, st);
00637                   v->BeginLoading();
00638                 } else { // leave stations without docks right aways
00639                   v->current_order.MakeLeaveStation();
00640                   v->cur_order_index++;
00641                   InvalidateVehicleOrder(v, 0);
00642                 }
00643               }
00644             }
00645           }
00646         }
00647       }
00648     } else {
00649       DiagDirection diagdir;
00650       /* New tile */
00651       if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
00652         goto reverse_direction;
00653       }
00654 
00655       dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
00656       assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
00657       diagdir = DirToDiagDir(dir);
00658       tracks = GetAvailShipTracks(gp.new_tile, diagdir);
00659       if (tracks == TRACK_BIT_NONE) goto reverse_direction;
00660 
00661       /* Choose a direction, and continue if we find one */
00662       track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
00663       if (track == INVALID_TRACK) goto reverse_direction;
00664 
00665       b = _ship_subcoord[diagdir][track];
00666 
00667       gp.x = (gp.x & ~0xF) | b[0];
00668       gp.y = (gp.y & ~0xF) | b[1];
00669 
00670       /* Call the landscape function and tell it that the vehicle entered the tile */
00671       r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
00672       if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
00673 
00674       if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
00675         v->tile = gp.new_tile;
00676         v->u.ship.state = TrackToTrackBits(track);
00677       }
00678 
00679       v->direction = (Direction)b[2];
00680     }
00681   } else {
00682     /* On a bridge */
00683     if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
00684       v->x_pos = gp.x;
00685       v->y_pos = gp.y;
00686       VehiclePositionChanged(v);
00687       if (!(v->vehstatus & VS_HIDDEN)) EndVehicleMove(v);
00688       return;
00689     }
00690   }
00691 
00692   /* update image of ship, as well as delta XY */
00693   dir = ShipGetNewDirection(v, gp.x, gp.y);
00694   v->x_pos = gp.x;
00695   v->y_pos = gp.y;
00696   v->z_pos = GetSlopeZ(gp.x, gp.y);
00697 
00698 getout:
00699   v->UpdateDeltaXY(dir);
00700   v->cur_image = v->GetImage(dir);
00701   VehiclePositionChanged(v);
00702   EndVehicleMove(v);
00703   return;
00704 
00705 reverse_direction:
00706   dir = ReverseDir(v->direction);
00707   v->direction = dir;
00708   goto getout;
00709 }
00710 
00711 static void AgeShipCargo(Vehicle *v)
00712 {
00713   if (_age_cargo_skip_counter != 0) return;
00714   v->cargo.AgeCargo();
00715 }
00716 
00717 void Ship::Tick()
00718 {
00719   if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
00720 
00721   AgeShipCargo(this);
00722   ShipController(this);
00723 }
00724 
00731 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00732 {
00733   UnitID unit_num;
00734 
00735   if (!IsEngineBuildable(p1, VEH_SHIP, _current_company)) return_cmd_error(STR_SHIP_NOT_AVAILABLE);
00736 
00737   const Engine *e = GetEngine(p1);
00738   CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost());
00739 
00740   if (flags & DC_QUERY_COST) return value;
00741 
00742   /* The ai_new queries the vehicle cost before building the route,
00743    * so we must check against cheaters no sooner than now. --pasky */
00744   if (!IsShipDepotTile(tile)) return CMD_ERROR;
00745   if (!IsTileOwner(tile, _current_company)) return CMD_ERROR;
00746 
00747   unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_SHIP);
00748 
00749   if (!Vehicle::CanAllocateItem() || unit_num > _settings_game.vehicle.max_ships)
00750     return_cmd_error(STR_00E1_TOO_MANY_VEHICLES_IN_GAME);
00751 
00752   if (flags & DC_EXEC) {
00753     int x;
00754     int y;
00755 
00756     const ShipVehicleInfo *svi = ShipVehInfo(p1);
00757 
00758     Vehicle *v = new Ship();
00759     v->unitnumber = unit_num;
00760 
00761     v->owner = _current_company;
00762     v->tile = tile;
00763     x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
00764     y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
00765     v->x_pos = x;
00766     v->y_pos = y;
00767     v->z_pos = GetSlopeZ(x, y);
00768 
00769     v->running_ticks = 0;
00770 
00771     v->UpdateDeltaXY(v->direction);
00772     v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
00773 
00774     v->spritenum = svi->image_index;
00775     v->cargo_type = svi->cargo_type;
00776     v->cargo_subtype = 0;
00777     v->cargo_cap = svi->capacity;
00778     v->value = value.GetCost();
00779 
00780     v->last_station_visited = INVALID_STATION;
00781     v->max_speed = svi->max_speed;
00782     v->engine_type = p1;
00783 
00784     v->reliability = e->reliability;
00785     v->reliability_spd_dec = e->reliability_spd_dec;
00786     v->max_age = e->lifelength * DAYS_IN_LEAP_YEAR;
00787     _new_vehicle_id = v->index;
00788 
00789     v->name = NULL;
00790     v->u.ship.state = TRACK_BIT_DEPOT;
00791 
00792     v->service_interval = _settings_game.vehicle.servint_ships;
00793     v->date_of_last_service = _date;
00794     v->build_year = _cur_year;
00795     v->cur_image = 0x0E5E;
00796     v->random_bits = VehicleRandomBits();
00797 
00798     v->vehicle_flags = 0;
00799     if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
00800 
00801     v->cargo_cap = GetVehicleProperty(v, 0x0D, svi->capacity);
00802 
00803     VehiclePositionChanged(v);
00804 
00805     InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
00806     InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
00807     InvalidateWindow(WC_COMPANY, v->owner);
00808     if (IsLocalCompany())
00809       InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Ship window
00810 
00811     GetCompany(_current_company)->num_engines[p1]++;
00812   }
00813 
00814   return value;
00815 }
00816 
00823 CommandCost CmdSellShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00824 {
00825   Vehicle *v;
00826 
00827   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00828 
00829   v = GetVehicle(p1);
00830 
00831   if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
00832 
00833   if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
00834 
00835   if (!v->IsStoppedInDepot()) {
00836     return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
00837   }
00838 
00839   CommandCost ret(EXPENSES_NEW_VEHICLES, -v->value);
00840 
00841   if (flags & DC_EXEC) {
00842     delete v;
00843   }
00844 
00845   return ret;
00846 }
00847 
00848 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
00849 {
00850   const Depot *depot = FindClosestShipDepot(this);
00851 
00852   if (depot == NULL) return false;
00853 
00854   if (location    != NULL) *location    = depot->xy;
00855   if (destination != NULL) *destination = depot->index;
00856 
00857   return true;
00858 }
00859 
00868 CommandCost CmdSendShipToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00869 {
00870   if (p2 & DEPOT_MASS_SEND) {
00871     /* Mass goto depot requested */
00872     if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
00873     return SendAllVehiclesToDepot(VEH_SHIP, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
00874   }
00875 
00876   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00877 
00878   Vehicle *v = GetVehicle(p1);
00879 
00880   if (v->type != VEH_SHIP) return CMD_ERROR;
00881 
00882   return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
00883 }
00884 
00885 
00896 CommandCost CmdRefitShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00897 {
00898   Vehicle *v;
00899   CommandCost cost(EXPENSES_SHIP_RUN);
00900   CargoID new_cid = GB(p2, 0, 8); //gets the cargo number
00901   byte new_subtype = GB(p2, 8, 8);
00902   uint16 capacity = CALLBACK_FAILED;
00903 
00904   if (!IsValidVehicleID(p1)) return CMD_ERROR;
00905 
00906   v = GetVehicle(p1);
00907 
00908   if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
00909   if (!v->IsStoppedInDepot()) return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
00910   if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
00911 
00912   /* Check cargo */
00913   if (!ShipVehInfo(v->engine_type)->refittable) return CMD_ERROR;
00914   if (new_cid >= NUM_CARGO || !CanRefitTo(v->engine_type, new_cid)) return CMD_ERROR;
00915 
00916   /* Check the refit capacity callback */
00917   if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
00918     /* Back up the existing cargo type */
00919     CargoID temp_cid = v->cargo_type;
00920     byte temp_subtype = v->cargo_subtype;
00921     v->cargo_type = new_cid;
00922     v->cargo_subtype = new_subtype;
00923 
00924     capacity = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
00925 
00926     /* Restore the cargo type */
00927     v->cargo_type = temp_cid;
00928     v->cargo_subtype = temp_subtype;
00929   }
00930 
00931   if (capacity == CALLBACK_FAILED) {
00932     capacity = GetVehicleProperty(v, 0x0D, ShipVehInfo(v->engine_type)->capacity);
00933   }
00934   _returned_refit_capacity = capacity;
00935 
00936   if (new_cid != v->cargo_type) {
00937     cost = GetRefitCost(v->engine_type);
00938   }
00939 
00940   if (flags & DC_EXEC) {
00941     v->cargo_cap = capacity;
00942     v->cargo.Truncate((v->cargo_type == new_cid) ? capacity : 0);
00943     v->cargo_type = new_cid;
00944     v->cargo_subtype = new_subtype;
00945     v->colourmap = PAL_NONE; // invalidate vehicle colour map
00946     InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
00947     InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
00948     InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
00949   }
00950 
00951   return cost;
00952 
00953 }

Generated on Mon Feb 16 23:12:10 2009 for openttd by  doxygen 1.5.6