35 #include "table/strings.h" 40 const uint32 _veh_build_proc_table[] = {
47 const uint32 _veh_sell_proc_table[] = {
54 const uint32 _veh_refit_proc_table[] = {
61 const uint32 _send_to_depot_proc_table[] = {
107 case VEH_SHIP: num_vehicles = 1;
break;
109 default: NOT_REACHED();
117 if (unit_num == UINT16_MAX)
return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
125 default: NOT_REACHED();
128 if (value.Succeeded() && flags &
DC_EXEC) {
130 v->
value = value.GetCost();
173 if (ret.
Failed())
return ret;
218 if (e->
GetGRF() != NULL) {
224 *auto_refit_allowed =
HasBit(cb_res, 14);
225 int factor =
GB(cb_res, 0, 14);
226 if (factor >= 0x2000) factor -= 0x4000;
231 *auto_refit_allowed = e->info.refit_cost == 0;
232 return (v == NULL || v->
cargo_type != new_cid) ? e->info.refit_cost : 0;
249 int cost_factor =
GetRefitCostFactor(v, engine_type, new_cid, new_subtype, auto_refit_allowed);
252 base_price = PR_BUILD_VEHICLE_SHIP;
257 base_price = PR_BUILD_VEHICLE_ROAD;
262 base_price = PR_BUILD_VEHICLE_AIRCRAFT;
267 base_price = (e->u.rail.railveh_type ==
RAILVEH_WAGON) ? PR_BUILD_VEHICLE_WAGON : PR_BUILD_VEHICLE_TRAIN;
272 default: NOT_REACHED();
274 if (cost_factor < 0) {
304 uint total_capacity = 0;
305 uint total_mail_capacity = 0;
306 num_vehicles = num_vehicles == 0 ? UINT8_MAX : num_vehicles;
316 refit_result.
Clear();
319 byte actual_subtype = new_subtype;
320 for (; v != NULL; v = (only_this ? NULL : v->
Next())) {
332 if (!refittable && v->
cargo_type != new_cid)
continue;
335 if (actual_subtype == 0xFF) {
349 total_capacity += amount;
353 if (!refittable)
continue;
359 bool auto_refit_allowed;
361 if (auto_refit && (flags &
DC_QUERY_COST) == 0 && !auto_refit_allowed) {
365 total_capacity -= amount;
375 cost.AddCost(refit_cost);
390 result->
subtype = actual_subtype;
411 refit_result.
Clear();
444 if (ret.
Failed())
return ret;
446 bool auto_refit =
HasBit(p2, 6);
464 byte new_subtype =
GB(p2, 8, 8);
469 uint8 num_vehicles =
GB(p2, 16, 8);
494 default: NOT_REACHED();
529 if (ret.
Failed())
return ret;
557 if (v->
GetGRF()->grf_version < 8) {
561 if (callback < 0x400) {
569 error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES;
605 bool do_start =
HasBit(p1, 0);
606 bool vehicle_list_window =
HasBit(p1, 1);
612 if (vehicle_list_window) {
619 for (uint i = 0; i < list.
Length(); i++) {
647 VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
651 uint sell_command = GetCmdSellVeh(vehicle_type);
657 bool had_success =
false;
658 for (uint i = 0; i < list.
Length(); i++) {
668 return had_success ? cost : last_error;
684 VehicleType vehicle_type = Extract<VehicleType, 0, 3>(p1);
692 for (uint i = 0; i < list.
Length(); i++) {
715 if (v->
name != NULL && strcmp(v->
name, name) == 0)
return false;
731 size_t number_position;
732 for (number_position = strlen(src->
name); number_position > 0; number_position--) {
735 if (src->
name[number_position - 1] <
'0' || src->
name[number_position - 1] >
'9')
break;
741 if (number_position == strlen(src->
name)) {
745 number_position = strlen(buf);
750 buf[number_position] =
'\0';
752 num = strtol(&src->
name[number_position], &endptr, 10) + 1;
753 padding = endptr - &src->
name[number_position];
757 for (
int max_iterations = 1000; max_iterations > 0; max_iterations--, num++) {
759 seprintf(&buf[number_position],
lastof(buf),
"%0*d", padding, num);
800 if (ret.
Failed())
return ret;
809 }
while ((v = v->
Next()) != NULL);
837 if (w_front != NULL)
DoCommand(w_front->
tile, w_front->
index | (1 << 20), 0, flags, GetCmdSellVeh(w_front));
843 if (flags & DC_EXEC) {
865 w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom());
866 w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent());
874 _new_vehicle_id = w_front->
index;
877 if (flags & DC_EXEC) {
895 if (flags & DC_EXEC) {
930 if (flags & DC_EXEC) {
945 if (flags & DC_EXEC) {
969 bool had_success =
false;
970 for (uint i = 0; i < list.
Length(); i++) {
1030 if (ret.
Failed())
return ret;
1068 if (ret.
Failed())
return ret;
1071 bool iscustom =
HasBit(p2, 16);
1076 serv_int =
GB(p2, 0, 16);
1083 v->SetServiceInterval(serv_int);
1084 v->SetServiceIntervalIsCustom(iscustom);
1085 v->SetServiceIntervalIsPercent(ispercent);
bool IsEngineBuildable(EngineID engine, VehicleType type, CompanyID company)
Check if an engine is buildable.
CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a ship.
VehicleSettings vehicle
options for vehicles
static bool IsLocalCompany()
Is the current company the local company?
Vehicle is stopped by the player.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition of stuff that is very close to a company, like the company struct itself.
CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Build a vehicle.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Money value
Value of the vehicle.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
The information about a vehicle list.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Functions related to the autoreplace GUIs.
uint16 GetServiceIntervalClamped(uint interval, bool ispercent)
Clamp the service interval to the correct min/max.
Don't cancel current goto depot command if any.
Functions and type for generating vehicle lists.
CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint32 user)
Sell a (single) train wagon/engine.
static Titem * Get(size_t index)
Returns Titem with given index.
bool CanCarryCargo() const
Determines whether an engine can carry something.
Conventional Take Off and Landing, i.e. planes.
Vehicle * v
Vehicle to refit.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Helper structure for RefitVehicle()
Base for the train class.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
uint16 cur_speed
current speed
query cost only, don't build.
uint Truncate(uint max_move=UINT_MAX)
Truncates the cargo in this list to the given amount.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Depot view; Window numbers:
Base class for groups and group functions.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
Specification of a cargo type.
OrderList * list
Pointer to the order list for this vehicle.
byte GetBestFittingSubType(Vehicle *v_from, Vehicle *v_for, CargoID dest_cargo_type)
Get the best fitting subtype when 'cloning'/'replacing' v_from with v_for.
Functions related to vehicles.
Aircraft, helicopters, rotors and their shadows belong to this class.
CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sells all vehicles in a depot.
Called when the company (or AI) tries to start or stop a vehicle.
Price
Enumeration of all base prices for use with Prices.
void Clear()
Remove all items from the list.
bool UnpackIfValid(uint32 data)
Unpack a VehicleListIdentifier from a single uint32.
const T * Begin() const
Get the pointer to the first item (const)
static int GetRefitCostFactor(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
Helper to run the refit cost callback.
Tindex index
Index of this pool item.
uint TotalCount() const
Returns sum of cargo, including reserved cargo.
Helper functions to extract data from command parameters.
void BuildDepotVehicleList(VehicleType type, TileIndex tile, VehicleList *engines, VehicleList *wagons, bool individual_wagons)
Generate a list of vehicles inside a depot.
bool GenerateVehicleSortList(VehicleList *list, const VehicleListIdentifier &vli)
Generate a list of vehicles based on window type.
#define lastof(x)
Get the last element of an fixed size array.
Simple vector template class.
clone (and share) an order
StringID GetGRFStringID(uint32 grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
void CargoChanged()
Recalculates the cached weight of a vehicle and its parts.
Common return value for all commands.
uint32 cached_power
Total power of the consist (valid only for the first engine).
CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Starts or stops a lot of vehicles.
uint16 classes
Classes of this cargo type.
UnitID GetFreeUnitNumber(VehicleType type)
Get an unused unit number for a vehicle (if allowed).
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
CompanySettings settings
settings specific for each company
const T * End() const
Get the pointer behind the last valid item (const)
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
CargoID GetDefaultCargoType() const
Determines the default cargo type of an engine.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Autoreplace all vehicles in the depot.
CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Give a custom name to your vehicle.
DepotCommand
Flags to add to p1 for goto depot commands.
T * Append(uint to_add=1)
Append an item and return it.
CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Clone a vehicle.
replace/renew a vehicle while it is in a depot
uint16 service_interval
The interval for (automatic) servicing; either in days or %.
Called to determine the cost factor for refitting a vehicle.
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
uint16 cargo_cap
total capacity
Various declarations for airports.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Header of Action 04 "universal holder" structure and functions.
Map related accessors for depots.
static const uint32 MAKE_ORDER_BACKUP_FLAG
Flag to pass to the vehicle construction command when an order should be preserved.
Functions related to low-level strings.
void UpdateCache()
Update the caches of this ship.
Money GetCost() const
Return how much a new engine costs.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
static const uint MAX_LENGTH_VEHICLE_NAME_CHARS
The maximum length of a vehicle name in characters including '\0'.
UnitID unitnumber
unit number, for display purposes only
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
byte cargo_subtype
Used for livery refits (NewGRF variations)
uint Length() const
Get the number of items in the list.
byte subtype
Type of aircraft.
uint16 crash_anim_pos
Crash animation counter.
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
void DeleteVehicleNews(VehicleID vid, StringID news)
Delete a news item type about a vehicle.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
bool Contains(const T &item) const
Tests whether a item is present in the vector.
VehicleDefaultSettings vehicle
default settings for vehicles
Functions related to engines.
VehicleType
Available vehicle types.
refit the cargo space of a vehicle
byte subtype
cargo subtype to refit to
bool IsType(OrderType type) const
Check whether this order is of the given type.
DoCommandFlag
List of flags for a command.
simple wagon, not motorized
bool Succeeded() const
Did this command succeed?
static CommandCost GetRefitCost(const Vehicle *v, EngineID engine_type, CargoID new_cid, byte new_subtype, bool *auto_refit_allowed)
Learn the price of refitting a certain engine.
Definition of base types and functions in a cross-platform compatible way.
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Tells that it's a mass send to depot command (type in VLW flag)
bool IsArticulatedPart() const
Check if the vehicle is an articulated part of an engine.
A number of safeguards to prevent using unsafe methods.
void InvalidateNewGRFCacheOfChain()
Invalidates cached NewGRF variables of all vehicles in the chain (after the current vehicle) ...
Vehicle * GetNextVehicle() const
Get the next real (non-articulated part) vehicle in the consist.
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
CargoID cargo_type
type of cargo this vehicle is carrying
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Vehicle view; Window numbers:
static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, CargoID new_cid, byte new_subtype, DoCommandFlag flags, bool auto_refit)
Refits a vehicle (chain).
Functions related to order backups.
bool IsFrontEngine() const
Check if the vehicle is a front engine.
bool IsShared() const
Is this a shared order list?
byte misc_flags
Miscellaneous flags.
TileIndex tile
Current tile index.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
ExpensesType
Types of expenses.
Valid changes for autorefitting in stations.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
uint capacity
New capacity of vehicle.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
uint8 cargo_map[NUM_CARGO]
Inverse cargo translation table (CargoID -> local ID)
Airplane has arrived at a runway for take-off.
static VehicleType GetDepotVehicleType(TileIndex t)
Get the type of vehicles that can use a depot.
static T min(const T a, const T b)
Returns the minimum of two values.
uint16 refit_cap
Capacity left over from before last refit.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
bool Failed() const
Did this command fail?
static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, const VehicleListIdentifier &vli)
Send all vehicles of type to depots.
CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a road vehicle.
void InvalidateAutoreplaceWindow(EngineID e, GroupID id_g)
Rebuild the left autoreplace list if an engine is removed or added.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
byte state
State of the airport.
uint DetermineCapacity(const Vehicle *v, uint16 *mail_capacity=NULL) const
Determines capacity of a given vehicle from scratch.
autoreplace/autorenew is in progress, this shall disable vehicle limits when building, and ignore certain restrictions when undoing things (like vehicle attach callback)
Maximal number of cargo types in a game.
CommandCost CmdBuildAircraft(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build an aircraft.
uint CountArticulatedParts(EngineID engine_type, bool purchase_window)
Count the number of articulated parts of an engine.
char * name
Name of vehicle.
execute the given command
The vehicle will leave the depot right after arrival (serivce only)
Functions related to companies.
Functions related to articulated vehicles.
Automatic refitting is allowed.
Running costs road vehicles.
bool IsGroundVehicle() const
Check if the vehicle is a ground vehicle.
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting)
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
uint16 EngineID
Unique identification number of an engine.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
CompanyByte _current_company
Company currently doing an action.
uint32 TileIndex
The index/ID of a Tile.
Vehicle * Next() const
Get the next vehicle of this vehicle.
void GetVehicleSet(VehicleSet &set, Vehicle *v, uint8 num_vehicles)
Calculates the set of vehicles that will be affected by a given selection.
bool servint_ispercent
service intervals are in percents
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
OwnerByte owner
Which company owns the vehicle?
indicates a combination of two locomotives
Vehicle * GetNextArticulatedPart() const
Get the next part of an articulated engine.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
uint mail_capacity
New mail capacity of aircraft.
Reverse the visible direction of the vehicle.
uint16 _returned_mail_refit_capacity
Stores the mail capacity after a refit operation (Aircraft only).
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Vehicle details; Window numbers:
Functions related to commands.
CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Send a vehicle to the depot.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the vehicle is tied to.
uint16 UnitID
Type for the company global vehicle unit number.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Refits a vehicle to the specified cargo type.
CommandCost SendToDepot(DoCommandFlag flags, DepotCommand command)
Send this vehicle to the depot using the given command(s).
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
bool IsFreeWagon() const
Check if the vehicle is a free wagon (got no engine in front of it).
uint8 roadveh_acceleration_model
realistic acceleration for road vehicles
CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Change the service interval of a vehicle.
EngineID engine_type
The type of engine used for this vehicle.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
const GRFFile * GetGRF() const
Retrieve the NewGRF the vehicle is tied to.
send a vehicle to a depot
#define CMD_MSG(x)
Used to combine a StringID with the command.
byte CargoID
Cargo slots to indicate a cargo type within a game.
virtual bool IsChainInDepot() const
Check whether the whole vehicle chain is in the depot.
static bool IsDepotTile(TileIndex tile)
Is the given tile a tile with a depot on it?
static void Restore(Vehicle *v, uint32 user)
Restore the data of this order to the given vehicle.
static void Backup(const Vehicle *v, uint32 user)
Create an order backup for the given vehicle.
union Vehicle::@46 orders
The orders currently assigned to the vehicle.
move a rail vehicle (in the depot)
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Functions related to news.
Company view; Window numbers:
VehicleType vtype
The vehicle type associated with this list.
static void CloneVehicleName(const Vehicle *src, Vehicle *dst)
Clone the custom name of a vehicle, adding or incrementing a number.
CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell a vehicle.
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
VehicleTypeByte type
Type of vehicle.
Order current_order
The current order (+ status, like: loading)
VehicleOrderID GetNumOrders() const
Get number of orders in the order list.
GroupID group_id
Index of group Pool array.
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-...
Valid changes for refitting in a depot.
GroundVehicleCache gcache
Cache of often calculated values.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
static bool IsUniqueVehicleName(const char *name)
Test if a name is unique among vehicle names.
CommandCost CmdBuildRailVehicle(TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v)
Build a railroad vehicle.
CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Start/Stop a vehicle.
Base for the NewGRF implementation.