OpenTTD
ship_cmd.cpp
Go to the documentation of this file.
1 /* $Id: ship_cmd.cpp 26863 2014-09-20 15:31:26Z rubidium $ */
2 
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  */
9 
12 #include "stdafx.h"
13 #include "ship.h"
14 #include "landscape.h"
15 #include "timetable.h"
16 #include "news_func.h"
17 #include "company_func.h"
19 #include "depot_base.h"
20 #include "station_base.h"
21 #include "newgrf_engine.h"
22 #include "pathfinder/yapf/yapf.h"
23 #include "newgrf_sound.h"
24 #include "spritecache.h"
25 #include "strings_func.h"
26 #include "window_func.h"
27 #include "date_func.h"
28 #include "vehicle_func.h"
29 #include "sound_func.h"
30 #include "ai/ai.hpp"
32 #include "engine_base.h"
33 #include "company_base.h"
34 #include "tunnelbridge_map.h"
35 #include "zoom_func.h"
36 
37 #include "table/strings.h"
38 
39 #include "safeguards.h"
40 
47 {
48  if (HasTileWaterClass(tile)) return GetWaterClass(tile);
49  if (IsTileType(tile, MP_TUNNELBRIDGE)) {
51  return WATER_CLASS_CANAL;
52  }
53  if (IsTileType(tile, MP_RAILWAY)) {
54  assert(GetRailGroundType(tile) == RAIL_GROUND_WATER);
55  return WATER_CLASS_SEA;
56  }
57  NOT_REACHED();
58 }
59 
60 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
61 
62 template <>
63 bool IsValidImageIndex<VEH_SHIP>(uint8 image_index)
64 {
65  return image_index < lengthof(_ship_sprites);
66 }
67 
68 static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
69 {
71 }
72 
73 static SpriteID GetShipIcon(EngineID engine, EngineImageType image_type)
74 {
75  const Engine *e = Engine::Get(engine);
76  uint8 spritenum = e->u.ship.image_index;
77 
78  if (is_custom_sprite(spritenum)) {
79  SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W, image_type);
80  if (sprite != 0) return sprite;
81 
82  spritenum = e->original_image_index;
83  }
84 
85  assert(IsValidImageIndex<VEH_SHIP>(spritenum));
86  return DIR_W + _ship_sprites[spritenum];
87 }
88 
89 void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type)
90 {
91  SpriteID sprite = GetShipIcon(engine, image_type);
92  const Sprite *real_sprite = GetSprite(sprite, ST_NORMAL);
93  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));
94  DrawSprite(sprite, pal, preferred_x, y);
95 }
96 
106 void GetShipSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
107 {
108  const Sprite *spr = GetSprite(GetShipIcon(engine, image_type), ST_NORMAL);
109 
110  width = UnScaleByZoom(spr->width, ZOOM_LVL_GUI);
111  height = UnScaleByZoom(spr->height, ZOOM_LVL_GUI);
112  xoffs = UnScaleByZoom(spr->x_offs, ZOOM_LVL_GUI);
113  yoffs = UnScaleByZoom(spr->y_offs, ZOOM_LVL_GUI);
114 }
115 
116 SpriteID Ship::GetImage(Direction direction, EngineImageType image_type) const
117 {
118  uint8 spritenum = this->spritenum;
119 
120  if (is_custom_sprite(spritenum)) {
121  SpriteID sprite = GetCustomVehicleSprite(this, direction, image_type);
122  if (sprite != 0) return sprite;
123 
124  spritenum = this->GetEngine()->original_image_index;
125  }
126 
127  assert(IsValidImageIndex<VEH_SHIP>(spritenum));
128  return _ship_sprites[spritenum] + direction;
129 }
130 
131 static const Depot *FindClosestShipDepot(const Vehicle *v, uint max_distance)
132 {
133  /* Find the closest depot */
134  const Depot *depot;
135  const Depot *best_depot = NULL;
136  /* If we don't have a maximum distance, i.e. distance = 0,
137  * we want to find any depot so the best distance of no
138  * depot must be more than any correct distance. On the
139  * other hand if we have set a maximum distance, any depot
140  * further away than max_distance can safely be ignored. */
141  uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
142 
143  FOR_ALL_DEPOTS(depot) {
144  TileIndex tile = depot->xy;
145  if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
146  uint dist = DistanceManhattan(tile, v->tile);
147  if (dist < best_dist) {
148  best_dist = dist;
149  best_depot = depot;
150  }
151  }
152  }
153 
154  return best_depot;
155 }
156 
157 static void CheckIfShipNeedsService(Vehicle *v)
158 {
159  if (Company::Get(v->owner)->settings.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
160  if (v->IsChainInDepot()) {
162  return;
163  }
164 
165  uint max_distance;
167  case VPF_OPF: max_distance = 12; break;
170  default: NOT_REACHED();
171  }
172 
173  const Depot *depot = FindClosestShipDepot(v, max_distance);
174 
175  if (depot == NULL) {
176  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
179  }
180  return;
181  }
182 
184  v->dest_tile = depot->xy;
186 }
187 
192 {
193  const ShipVehicleInfo *svi = ShipVehInfo(this->engine_type);
194 
195  /* Get speed fraction for the current water type. Aqueducts are always canals. */
196  bool is_ocean = GetEffectiveWaterClass(this->tile) == WATER_CLASS_SEA;
197  uint raw_speed = GetVehicleProperty(this, PROP_SHIP_SPEED, svi->max_speed);
198  this->vcache.cached_max_speed = svi->ApplyWaterClassSpeedFrac(raw_speed, is_ocean);
199 
200  /* Update cargo aging period. */
201  this->vcache.cached_cargo_age_period = GetVehicleProperty(this, PROP_SHIP_CARGO_AGE_PERIOD, EngInfo(this->engine_type)->cargo_age_period);
202 
203  this->UpdateVisualEffect();
204 }
205 
207 {
208  const Engine *e = this->GetEngine();
209  uint cost_factor = GetVehicleProperty(this, PROP_SHIP_RUNNING_COST_FACTOR, e->u.ship.running_cost);
210  return GetPrice(PR_RUNNING_SHIP, cost_factor, e->GetGRF());
211 }
212 
214 {
215  if ((++this->day_counter & 7) == 0) {
216  DecreaseVehicleValue(this);
217  }
218 
219  CheckVehicleBreakdown(this);
220  AgeVehicle(this);
221  CheckIfShipNeedsService(this);
222 
223  CheckOrders(this);
224 
225  if (this->running_ticks == 0) return;
226 
228 
229  this->profit_this_year -= cost.GetCost();
230  this->running_ticks = 0;
231 
233 
235  /* we need this for the profit */
237 }
238 
240 {
241  if (this->vehstatus & VS_CRASHED) return INVALID_TRACKDIR;
242 
243  if (this->IsInDepot()) {
244  /* We'll assume the ship is facing outwards */
245  return DiagDirToDiagTrackdir(GetShipDepotDirection(this->tile));
246  }
247 
248  if (this->state == TRACK_BIT_WORMHOLE) {
249  /* ship on aqueduct, so just use his direction and assume a diagonal track */
251  }
252 
254 }
255 
257 {
258  this->colourmap = PAL_NONE;
259  this->UpdateViewport(true, false);
260  this->UpdateCache();
261 }
262 
263 static void PlayShipSound(const Vehicle *v)
264 {
265  if (!PlayVehicleSound(v, VSE_START)) {
266  SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
267  }
268 }
269 
271 {
272  PlayShipSound(this);
273 }
274 
276 {
277  if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
278 
279  const Station *st = Station::Get(station);
280  if (st->dock_tile != INVALID_TILE) {
282  } else {
283  this->IncrementRealOrderIndex();
284  return 0;
285  }
286 }
287 
289 {
290  static const int8 _delta_xy_table[8][4] = {
291  /* y_extent, x_extent, y_offs, x_offs */
292  { 6, 6, -3, -3}, // N
293  { 6, 32, -3, -16}, // NE
294  { 6, 6, -3, -3}, // E
295  {32, 6, -16, -3}, // SE
296  { 6, 6, -3, -3}, // S
297  { 6, 32, -3, -16}, // SW
298  { 6, 6, -3, -3}, // W
299  {32, 6, -16, -3}, // NW
300  };
301 
302  const int8 *bb = _delta_xy_table[direction];
303  this->x_offs = bb[3];
304  this->y_offs = bb[2];
305  this->x_extent = bb[1];
306  this->y_extent = bb[0];
307  this->z_extent = 6;
308 }
309 
310 static const TileIndexDiffC _ship_leave_depot_offs[] = {
311  {-1, 0},
312  { 0, -1}
313 };
314 
315 static bool CheckShipLeaveDepot(Ship *v)
316 {
317  if (!v->IsChainInDepot()) return false;
318 
319  /* We are leaving a depot, but have to go to the exact same one; re-enter */
320  if (v->current_order.IsType(OT_GOTO_DEPOT) &&
323  return true;
324  }
325 
326  TileIndex tile = v->tile;
327  Axis axis = GetShipDepotAxis(tile);
328 
329  DiagDirection north_dir = ReverseDiagDir(AxisToDiagDir(axis));
330  TileIndex north_neighbour = TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis]));
331  DiagDirection south_dir = AxisToDiagDir(axis);
332  TileIndex south_neighbour = TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis]));
333 
334  TrackBits north_tracks = DiagdirReachesTracks(north_dir) & GetTileShipTrackStatus(north_neighbour);
335  TrackBits south_tracks = DiagdirReachesTracks(south_dir) & GetTileShipTrackStatus(south_neighbour);
336  if (north_tracks && south_tracks) {
337  /* Ask pathfinder for best direction */
338  bool reverse = false;
339  bool path_found;
341  case VPF_OPF: reverse = OPFShipChooseTrack(v, north_neighbour, north_dir, north_tracks, path_found) == INVALID_TRACK; break; // OPF always allows reversing
342  case VPF_NPF: reverse = NPFShipCheckReverse(v); break;
343  case VPF_YAPF: reverse = YapfShipCheckReverse(v); break;
344  default: NOT_REACHED();
345  }
346  if (reverse) north_tracks = TRACK_BIT_NONE;
347  }
348 
349  if (north_tracks) {
350  /* Leave towards north */
351  v->direction = DiagDirToDir(north_dir);
352  } else if (south_tracks) {
353  /* Leave towards south */
354  v->direction = DiagDirToDir(south_dir);
355  } else {
356  /* Both ways blocked */
357  return false;
358  }
359 
360  v->state = AxisToTrackBits(axis);
361  v->vehstatus &= ~VS_HIDDEN;
362 
363  v->cur_speed = 0;
364  v->UpdateViewport(true, true);
366 
367  PlayShipSound(v);
371 
372  return false;
373 }
374 
375 static bool ShipAccelerate(Vehicle *v)
376 {
377  uint spd;
378  byte t;
379 
380  spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
381  spd = min(spd, v->current_order.GetMaxSpeed() * 2);
382 
383  /* updates statusbar only if speed have changed to save CPU time */
384  if (spd != v->cur_speed) {
385  v->cur_speed = spd;
387  }
388 
389  /* Convert direction-independent speed into direction-dependent speed. (old movement method) */
390  spd = v->GetOldAdvanceSpeed(spd);
391 
392  if (spd == 0) return false;
393  if ((byte)++spd == 0) return true;
394 
395  v->progress = (t = v->progress) - (byte)spd;
396 
397  return (t < v->progress);
398 }
399 
405 static void ShipArrivesAt(const Vehicle *v, Station *st)
406 {
407  /* Check if station was ever visited before */
408  if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
409  st->had_vehicle_of_type |= HVOT_SHIP;
410 
411  SetDParam(0, st->index);
413  STR_NEWS_FIRST_SHIP_ARRIVAL,
415  v->index,
416  st->index
417  );
418  AI::NewEvent(v->owner, new ScriptEventStationFirstVehicle(st->index, v->index));
419  }
420 }
421 
422 
432 static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
433 {
434  assert(IsValidDiagDirection(enterdir));
435 
436  bool path_found = true;
437  Track track;
439  case VPF_OPF: track = OPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
440  case VPF_NPF: track = NPFShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
441  case VPF_YAPF: track = YapfShipChooseTrack(v, tile, enterdir, tracks, path_found); break;
442  default: NOT_REACHED();
443  }
444 
445  v->HandlePathfindingResult(path_found);
446  return track;
447 }
448 
449 static const Direction _new_vehicle_direction_table[] = {
452  DIR_E , DIR_SE, DIR_S
453 };
454 
455 static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
456 {
457  uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
458  TileX(new_tile) - TileX(old_tile) + 1;
459  assert(offs < 11 && offs != 3 && offs != 7);
460  return _new_vehicle_direction_table[offs];
461 }
462 
463 static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
464 {
465  uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
466  assert(offs < 11 && offs != 3 && offs != 7);
467  return _new_vehicle_direction_table[offs];
468 }
469 
470 static inline TrackBits GetAvailShipTracks(TileIndex tile, DiagDirection dir)
471 {
472  return GetTileShipTrackStatus(tile) & DiagdirReachesTracks(dir);
473 }
474 
475 static const byte _ship_subcoord[4][6][3] = {
476  {
477  {15, 8, 1},
478  { 0, 0, 0},
479  { 0, 0, 0},
480  {15, 8, 2},
481  {15, 7, 0},
482  { 0, 0, 0},
483  },
484  {
485  { 0, 0, 0},
486  { 8, 0, 3},
487  { 7, 0, 2},
488  { 0, 0, 0},
489  { 8, 0, 4},
490  { 0, 0, 0},
491  },
492  {
493  { 0, 8, 5},
494  { 0, 0, 0},
495  { 0, 7, 6},
496  { 0, 0, 0},
497  { 0, 0, 0},
498  { 0, 8, 4},
499  },
500  {
501  { 0, 0, 0},
502  { 8, 15, 7},
503  { 0, 0, 0},
504  { 8, 15, 6},
505  { 0, 0, 0},
506  { 7, 15, 0},
507  }
508 };
509 
510 static void ShipController(Ship *v)
511 {
512  uint32 r;
513  const byte *b;
514  Direction dir;
515  Track track;
516  TrackBits tracks;
517 
518  v->tick_counter++;
519  v->current_order_time++;
520 
521  if (v->HandleBreakdown()) return;
522 
523  if (v->vehstatus & VS_STOPPED) return;
524 
525  ProcessOrders(v);
526  v->HandleLoading();
527 
528  if (v->current_order.IsType(OT_LOADING)) return;
529 
530  if (CheckShipLeaveDepot(v)) return;
531 
532  v->ShowVisualEffect();
533 
534  if (!ShipAccelerate(v)) return;
535 
537  if (v->state != TRACK_BIT_WORMHOLE) {
538  /* Not on a bridge */
539  if (gp.old_tile == gp.new_tile) {
540  /* Staying in tile */
541  if (v->IsInDepot()) {
542  gp.x = v->x_pos;
543  gp.y = v->y_pos;
544  } else {
545  /* Not inside depot */
546  r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
547  if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
548 
549  /* A leave station order only needs one tick to get processed, so we can
550  * always skip ahead. */
551  if (v->current_order.IsType(OT_LEAVESTATION)) {
552  v->current_order.Free();
554  } else if (v->dest_tile != 0) {
555  /* We have a target, let's see if we reached it... */
556  if (v->current_order.IsType(OT_GOTO_WAYPOINT) &&
557  DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
558  /* We got within 3 tiles of our target buoy, so let's skip to our
559  * next order */
560  UpdateVehicleTimetable(v, true);
563  } else {
564  /* Non-buoy orders really need to reach the tile */
565  if (v->dest_tile == gp.new_tile) {
566  if (v->current_order.IsType(OT_GOTO_DEPOT)) {
567  if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
569  return;
570  }
571  } else if (v->current_order.IsType(OT_GOTO_STATION)) {
573 
574  /* Process station in the orderlist. */
576  if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
577  ShipArrivesAt(v, st);
578  v->BeginLoading();
579  } else { // leave stations without docks right aways
582  }
583  }
584  }
585  }
586  }
587  }
588  } else {
589  /* New tile */
590  if (!IsValidTile(gp.new_tile)) goto reverse_direction;
591 
592  dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
593  assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
594  DiagDirection diagdir = DirToDiagDir(dir);
595  tracks = GetAvailShipTracks(gp.new_tile, diagdir);
596  if (tracks == TRACK_BIT_NONE) goto reverse_direction;
597 
598  /* Choose a direction, and continue if we find one */
599  track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
600  if (track == INVALID_TRACK) goto reverse_direction;
601 
602  b = _ship_subcoord[diagdir][track];
603 
604  gp.x = (gp.x & ~0xF) | b[0];
605  gp.y = (gp.y & ~0xF) | b[1];
606 
607  /* Call the landscape function and tell it that the vehicle entered the tile */
608  r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
609  if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
610 
611  if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
612  v->tile = gp.new_tile;
613  v->state = TrackToTrackBits(track);
614 
615  /* Update ship cache when the water class changes. Aqueducts are always canals. */
618  if (old_wc != new_wc) v->UpdateCache();
619  }
620 
621  v->direction = (Direction)b[2];
622  }
623  } else {
624  /* On a bridge */
626  v->x_pos = gp.x;
627  v->y_pos = gp.y;
628  v->UpdatePosition();
629  if ((v->vehstatus & VS_HIDDEN) == 0) v->Vehicle::UpdateViewport(true);
630  return;
631  }
632  }
633 
634  /* update image of ship, as well as delta XY */
635  dir = ShipGetNewDirection(v, gp.x, gp.y);
636  v->x_pos = gp.x;
637  v->y_pos = gp.y;
638  v->z_pos = GetSlopePixelZ(gp.x, gp.y);
639 
640 getout:
641  v->UpdatePosition();
642  v->UpdateViewport(true, true);
643  return;
644 
645 reverse_direction:
646  dir = ReverseDir(v->direction);
647  v->direction = dir;
648  goto getout;
649 }
650 
652 {
653  if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
654 
655  ShipController(this);
656 
657  return true;
658 }
659 
669 CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
670 {
671  tile = GetShipDepotNorthTile(tile);
672  if (flags & DC_EXEC) {
673  int x;
674  int y;
675 
676  const ShipVehicleInfo *svi = &e->u.ship;
677 
678  Ship *v = new Ship();
679  *ret = v;
680 
681  v->owner = _current_company;
682  v->tile = tile;
683  x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2;
684  y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2;
685  v->x_pos = x;
686  v->y_pos = y;
687  v->z_pos = GetSlopePixelZ(x, y);
688 
689  v->UpdateDeltaXY(v->direction);
691 
692  v->spritenum = svi->image_index;
694  v->cargo_cap = svi->capacity;
695  v->refit_cap = 0;
696 
697  v->last_station_visited = INVALID_STATION;
698  v->last_loading_station = INVALID_STATION;
699  v->engine_type = e->index;
700 
701  v->reliability = e->reliability;
703  v->max_age = e->GetLifeLengthInDays();
704  _new_vehicle_id = v->index;
705 
706  v->state = TRACK_BIT_DEPOT;
707 
708  v->SetServiceInterval(Company::Get(_current_company)->settings.vehicle.servint_ships);
710  v->build_year = _cur_year;
711  v->cur_image = SPR_IMG_QUERY;
713 
714  v->UpdateCache();
715 
717  v->SetServiceIntervalIsPercent(Company::Get(_current_company)->settings.vehicle.servint_ispercent);
718 
720 
721  v->cargo_cap = e->DetermineCapacity(v);
722 
724 
725  v->UpdatePosition();
726  }
727 
728  return CommandCost();
729 }
730 
731 bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
732 {
733  const Depot *depot = FindClosestShipDepot(this, 0);
734 
735  if (depot == NULL) return false;
736 
737  if (location != NULL) *location = depot->xy;
738  if (destination != NULL) *destination = depot->index;
739 
740  return true;
741 }