38 #include "table/strings.h" 61 static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
64 bool IsValidImageIndex<VEH_SHIP>(uint8 image_index)
66 return image_index <
lengthof(_ship_sprites);
77 uint8 spritenum = e->u.ship.image_index;
79 if (is_custom_sprite(spritenum)) {
80 GetCustomVehicleIcon(engine,
DIR_W, image_type, result);
86 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
87 result->
Set(
DIR_W + _ship_sprites[spritenum]);
93 GetShipIcon(engine, image_type, &seq);
97 preferred_x =
Clamp(preferred_x,
116 GetShipIcon(engine, image_type, &seq);
121 width =
UnScaleGUI(rect.right - rect.left + 1);
122 height =
UnScaleGUI(rect.bottom - rect.top + 1);
131 if (is_custom_sprite(spritenum)) {
132 GetCustomVehicleSprite(
this, direction, image_type, result);
138 assert(IsValidImageIndex<VEH_SHIP>(spritenum));
139 result->
Set(_ship_sprites[spritenum] + direction);
142 static const Depot *FindClosestShipDepot(
const Vehicle *v, uint max_distance)
146 const Depot *best_depot = NULL;
152 uint best_dist = max_distance == 0 ? UINT_MAX : max_distance + 1;
154 FOR_ALL_DEPOTS(depot) {
158 if (dist < best_dist) {
168 static void CheckIfShipNeedsService(
Vehicle *v)
178 case VPF_OPF: max_distance = 12;
break;
181 default: NOT_REACHED();
184 const Depot *depot = FindClosestShipDepot(v, max_distance);
230 CheckVehicleBreakdown(
this);
232 CheckIfShipNeedsService(
this);
274 static void PlayShipSound(
const Vehicle *v)
277 SndPlayVehicleFx(ShipVehInfo(v->
engine_type)->sfx, v);
301 static const int8 _delta_xy_table[8][4] = {
313 const int8 *bb = _delta_xy_table[
direction];
321 static bool CheckShipLeaveDepot(
Ship *v)
342 if (north_tracks && south_tracks) {
344 bool reverse =
false;
350 default: NOT_REACHED();
358 }
else if (south_tracks) {
381 static bool ShipAccelerate(
Vehicle *v)
398 if (spd == 0)
return false;
399 if ((byte)++spd == 0)
return true;
414 if (!(st->had_vehicle_of_type &
HVOT_SHIP)) {
419 STR_NEWS_FIRST_SHIP_ARRIVAL,
443 bool path_found =
true;
449 default: NOT_REACHED();
461 static const byte _ship_subcoord[4][6][3] = {
496 static void ShipController(
Ship *v)
516 if (CheckShipLeaveDepot(v))
return;
520 if (!ShipAccelerate(v))
return;
553 if ((gp.x & 0xF) == 8 && (gp.
y & 0xF) == 8) {
580 tracks = GetAvailShipTracks(gp.
new_tile, diagdir);
587 b = _ship_subcoord[diagdir][track];
589 gp.x = (gp.x & ~0xF) | b[0];
590 gp.
y = (gp.
y & ~0xF) | b[1];
622 v->
z_pos = GetSlopePixelZ(gp.x, gp.
y);
639 ShipController(
this);
671 v->
z_pos = GetSlopePixelZ(x, y);
688 _new_vehicle_id = v->
index;
717 const Depot *depot = FindClosestShipDepot(
this, 0);
719 if (depot == NULL)
return false;
721 if (location != NULL) *location = depot->xy;
722 if (destination != NULL) *destination = depot->
index;
Information about a ship vehicle.
Functions related to OTTD's strings.
This vehicle is in the exclusive preview stage, either being used or being offered to a company...
uint16 reliability
Current reliability of the engine.
uint32 PaletteID
The number of the palette.
Vehicle is stopped by the player.
First vehicle arrived for competitor.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition of stuff that is very close to a company, like the company struct itself.
Functions for NewGRF engines.
void DecreaseVehicleValue(Vehicle *v)
Decrease the value of a vehicle.
static const int DAYS_IN_YEAR
days per year
static TransportType GetTunnelBridgeTransportType(TileIndex t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
void ShowVisualEffect() const
Draw visual effects (smoke and/or sparks) for a vehicle chain.
Track NPFShipChooseTrack(const Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found)
Finds the best path for given ship using NPF.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
static DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
static Axis GetShipDepotAxis(TileIndex t)
Get the axis of the ship depot.
DirectionByte direction
facing
static int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
void CheckOrders(const Vehicle *v)
Check the orders of a vehicle, to see if there are invalid orders and stuff.
Flag for an invalid DiagDirection.
Track YapfShipChooseTrack(const Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found)
Finds the best path for given ship using YAPF.
static Titem * Get(size_t index)
Returns Titem with given index.
Functions related to dates.
static WaterClass GetWaterClass(TileIndex t)
Get the water class at a tile.
void PlayLeaveStationSound() const
Play the sound associated with leaving the station.
static TileIndex GetShipDepotNorthTile(TileIndex t)
Get the most northern tile of a ship depot.
Use default vehicle palette.
void GetShipSpriteSize(EngineID engine, uint &width, uint &height, int &xoffs, int &yoffs, EngineImageType image_type)
Get the size of the sprite of a ship sprite heading west (used for lists).
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
bool Tick()
Calls the tick handler of the vehicle.
Track
These are used to specify a single track.
uint16 cur_speed
current speed
uint16 cached_cargo_age_period
Number of ticks before carried cargo is aged.
static TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
Depot view; Window numbers:
byte spritenum
currently displayed sprite index 0xfd == custom sprite, 0xfe == custom second head sprite 0xff == res...
void UpdateDeltaXY(Direction direction)
Updates the x and y offsets and the size of the sprite used for this vehicle.
The Original PathFinder (only for ships)
uint ApplyWaterClassSpeedFrac(uint raw_speed, bool is_ocean) const
Apply ocean/canal speed fraction to a velocity.
TileIndex dock_tile
The location of the dock.
StationID last_loading_station
Last station the vehicle has stopped at and could possibly leave from with any cargo loaded...
bool IsInDepot() const
Check whether the vehicle is in the depot.
TileIndex dest_tile
Heading for this tile.
NPFSettings npf
pathfinder settings for the new pathfinder
Functions related to vehicles.
void IncrementRealOrderIndex()
Advanced cur_real_order_index to the next real order, keeps care of the wrap-around and invalidates t...
uint32 current_order_time
How many ticks have passed since this order started.
static uint TileX(TileIndex tile)
Get the X component of a tile.
void VehicleEnterDepot(Vehicle *v)
Vehicle entirely entered the depot, update its status, orders, vehicle windows, service it...
void Draw(int x, int y, PaletteID default_pal, bool force_pal) const
Draw the sprite sequence.
PathfinderSettings pf
settings for all pathfinders
static void ShipArrivesAt(const Vehicle *v, Station *st)
Ship arrives at a dock.
Base for all depots (except hangars)
void Set(SpriteID sprite)
Assign a single sprite to the sequence.
TrackBitsByte state
The "track" the ship is following.
Tindex index
Index of this pool item.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
void UpdateViewport(bool force_update, bool update_delta)
Update vehicle sprite- and position caches.
StationID last_station_visited
The last station we stopped at.
uint16 reliability_spd_dec
Reliability decrease speed.
Money GetCost() const
The costs as made up to this moment.
void HandlePathfindingResult(bool path_found)
Handle the pathfinding result, especially the lost status.
Common return value for all commands.
EngineImageType
Visualisation contexts of vehicles and engines.
byte flags
Flags of the engine.
Year _cur_year
Current year, starting at 0.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
bool NeedsAutomaticServicing() const
Checks if the current order should be interrupted for a service-in-depot order.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
void OnNewDay()
Calls the new day handler of the vehicle.
static const uint TILE_SIZE
Tile size in world coordinates.
Entry point for OpenTTD to YAPF.
byte VehicleRandomBits()
Get a value for a vehicle's random_bits.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
VehicleSpriteSeq sprite_seq
Vehicle appearance.
Direction
Defines the 8 directions on the map.
uint16 max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
static bool IsValidTile(TileIndex tile)
Checks if a tile is valid.
bool YapfShipCheckReverse(const Ship *v)
Returns true if it is better to reverse the ship before leaving depot using YAPF. ...
TrackBits
Bitfield corresponding to Track.
uint16 cargo_cap
total capacity
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Vehicle is a prototype (accepted as exclusive preview).
static DiagDirection DiagdirBetweenTiles(TileIndex tile_from, TileIndex tile_to)
Determines the DiagDirection to get from one tile to another.
static TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
void UpdateCache()
Update the caches of this ship.
uint16 reliability_spd_dec
Speed of reliability decay between services (per day).
void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
Subtract money from a company, including the money fraction.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a give tiletype.
void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
int y
x and y position of the vehicle after moving
void AgeVehicle(Vehicle *v)
Update age of a vehicle.
bool IsValid() const
Check whether the sequence contains any sprites.
YAPFSettings yapf
pathfinder settings for the yet another pathfinder
void MakeDummy()
Makes this order a Dummy order.
int8 y_offs
y offset for vehicle sprite
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
bool IsType(OrderType type) const
Check whether this order is of the given type.
static DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DoCommandFlag
List of flags for a command.
The vehicle either entered a bridge, tunnel or depot tile (this includes the last tile of the bridge/...
Definition of base types and functions in a cross-platform compatible way.
A number of safeguards to prevent using unsafe methods.
byte x_extent
x-extent of vehicle bounding box
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle) ...
bool ProcessOrders(Vehicle *v)
Handle the orders of a vehicle and determine the next place to go to if needed.
WaterClass GetEffectiveWaterClass(TileIndex tile)
Determine the effective WaterClass for a ship travelling on a tile.
static const int YAPF_TILE_LENGTH
Length (penalty) of one tile with YAPF.
byte z_extent
z-extent of vehicle bounding box
Trackdir
Enumeration for tracks and directions.
Vehicle starting, i.e. leaving, the station.
Track OPFShipChooseTrack(const Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool &path_found)
returns the track to choose on the next tile, or -1 when it's better to reverse.
CargoID cargo_type
type of cargo this vehicle is carrying
static bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
Vehicle view; Window numbers:
Number of ticks before carried cargo is aged.
TileIndex tile
Current tile index.
Grass with a fence and shore or water on the free halftile.
Functions to access the new pathfinder.
static Trackdir TrackDirectionToTrackdir(Track track, Direction dir)
Maps a track and a full (8-way) direction to the trackdir that represents the track running in the gi...
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const
Gets the sprite to show for the given direction.
static Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
VehicleEnterTileStatus VehicleEnterTile(Vehicle *v, TileIndex tile, int x, int y)
Call the tile callback function for a vehicle entering a tile.
int8 x_offs
x offset for vehicle sprite
StationFacilityByte facilities
The facilities that this station has.
Sprite sequence for a vehicle part.
DiagDirection
Enumeration for diagonal directions.
#define lengthof(x)
Return the length of an fixed size array.
static T min(const T a, const T b)
Returns the minimum of two values.
static bool IsShipDepotTile(TileIndex t)
Is it a ship depot tile?
uint16 refit_cap
Capacity left over from before last refit.
byte random_bits
Bits used for determining which randomized variational spritegroups to use when drawing.
Functions related to sound.
uint16 reliability
Reliability.
Functions to cache sprites in memory.
byte tick_counter
Increased by one for each tick.
All ships have this type.
static DepotID GetDepotIndex(TileIndex t)
Get the index of which depot is attached to the tile.
Year build_year
Year the vehicle has been built.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=NULL) const
Determines capacity of a given vehicle from scratch.
static void NewEvent(CompanyID company, ScriptEvent *event)
Queue a new event for an AI.
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
static TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction...
TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
TileIndex old_tile
Current tile of the vehicle.
static TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between to tiles from a TileIndexDiffC struct.
Bitflag for a wormhole (used for tunnels)
execute the given command
static TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Functions related to companies.
static DiagDirection GetShipDepotDirection(TileIndex t)
Get the direction of the ship depot.
GetNewVehiclePosResult GetNewVehiclePos(const Vehicle *v)
Get position information of a vehicle when moving one pixel in the direction it is facing...
void UpdatePosition()
Update the position of the vehicle.
Flag for an invalid track.
Tunnel entry/exit and bridge heads.
DestinationID GetDestination() const
Gets the destination of this order.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
void VehicleServiceInDepot(Vehicle *v)
Service a vehicle and all subsequent vehicles in the consist.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
void MakeGoToDepot(DepotID destination, OrderDepotTypeFlags order, OrderNonStopFlags non_stop_type=ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, OrderDepotActionFlags action=ODATF_SERVICE_ONLY, CargoID cargo=CT_NO_REFIT)
Makes this order a Go To Depot order.
bool HandleBreakdown()
Handle all of the aspects of a vehicle breakdown This includes adding smoke and sounds, and ending the breakdown when appropriate.
uint16 EngineID
Unique identification number of an engine.
CompanyByte _current_company
Company currently doing an action.
Ships list; Window numbers:
uint32 TileIndex
The index/ID of a Tile.
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
void BeginLoading()
Prepare everything to begin the loading when arriving at a station.
void MakeLeaveStation()
Makes this order a Leave Station order.
Date date_of_last_service
Last date the vehicle had a service at a depot.
Position information of a vehicle after it moved.
First vehicle arrived for company.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
void Free()
'Free' the order
OwnerByte owner
Which company owns the vehicle?
Functions related to zooming.
Trackdir GetVehicleTrackdir() const
Returns the Trackdir on which the vehicle is currently located.
static Track FindFirstTrack(TrackBits tracks)
Returns first Track from TrackBits or INVALID_TRACK.
static TrackBits TrackStatusToTrackBits(TrackStatus ts)
Returns the present-track-information of a TrackStatus.
Functions related to OTTD's landscape.
static const int NPF_TILE_LENGTH
Length (penalty) of one tile with NPF.
Vehicle details; Window numbers:
Base functions for all Games.
uint32 maximum_go_to_depot_penalty
What is the maximum penalty that may be endured for going to a depot.
Original pathfinder for ships; very simple.
Functions that have tunnels and bridges in common.
uint8 original_image_index
Original vehicle image index, thus the image index of the overridden vehicle.
byte running_ticks
Number of ticks this vehicle was not stopped this day.
byte y_extent
y-extent of vehicle bounding box
static TileIndexDiffC GetDockOffset(TileIndex t)
Get the tileoffset from this tile a ship should target to get to this dock.
EngineID engine_type
The type of engine used for this vehicle.
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
static bool HasTileWaterClass(TileIndex t)
Checks whether the tile has an waterclass associated.
Functions related to NewGRF provided sounds.
Base functions for all AIs.
static const TileIndex INVALID_TILE
The very nice invalid tile marker.
byte progress
The percentage (if divided by 256) this vehicle already crossed the tile unit.
The vehicle cannot enter the tile.
Specification of a rectangle with absolute coordinates of all edges.
uint16 GetMaxSpeed() const
Get the maxmimum speed in km-ish/h a vehicle is allowed to reach on the way to the destination...
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
Window functions not directly related to making/drawing windows.
Flag for an invalid trackdir.
static DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
uint8 pathfinder_for_ships
the pathfinder to use for ships
#define TILE_ADD(x, y)
Adds to tiles together.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Functions related to news.
Base classes/functions for stations.
CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **ret)
Build a ship.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
static Direction ReverseDir(Direction d)
Return the reverse of a direction.
TileIndex new_tile
Tile of the vehicle after moving.
bool FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
Find the closest depot for this vehicle and tell us the location, DestinationID and whether we should...
This depot order is because of the servicing limit.
void HandleLoading(bool mode=false)
Handle the loading of the vehicle; when not it skips through dummy orders and does nothing in all oth...
bool NPFShipCheckReverse(const Ship *v)
Returns true if it is better to reverse the ship before leaving depot using NPF.
Axis
Allow incrementing of DiagDirDiff variables.
uint GetOldAdvanceSpeed(uint speed)
Determines the effective direction-specific vehicle movement speed.
void GetBounds(Rect *bounds) const
Determine shared bounds of all sprites.
Date GetLifeLengthInDays() const
Returns the vehicle's (not model's!) life length in days.
byte day_counter
Increased by one for each day.
Order current_order
The current order (+ status, like: loading)
static Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
void UpdateVisualEffect(bool allow_power_change=true)
Update the cached visual effect.
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Money GetRunningCost() const
Gets the running cost of a vehicle.
SpriteID colourmap
NOSAVE: cached colour mapping.
static Track ChooseShipTrack(Ship *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
Runs the pathfinder to choose a track to continue along.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Ship()
We don't want GCC to zero our struct! It already is zeroed and has an index!
static void AddVehicleNewsItem(StringID string, NewsType type, VehicleID vehicle, StationID station=INVALID_STATION)
Adds a newsitem referencing a vehicle.