OpenTTD Source 20260129-master-g2bb01bd0e4
command_type.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#ifndef COMMAND_TYPE_H
11#define COMMAND_TYPE_H
12
13#include "company_type.h"
14#include "economy_type.h"
15#include "strings_type.h"
16#include "tile_type.h"
17
18struct GRFFile;
19
28 bool success;
29 Owner owner = CompanyID::Invalid();
32
33public:
38
42 explicit CommandCost(StringID msg, StringID extra_msg = INVALID_STRING_ID) : cost(0), message(msg), expense_type(INVALID_EXPENSES), success(false), extra_message(extra_msg) {}
43
49
55 CommandCost(ExpensesType ex_t, const Money &cst) : cost(cst), message(INVALID_STRING_ID), expense_type(ex_t), success(true) {}
56
62 {
63 this->owner = owner;
64 }
65
73 {
74 this->encoded_message = std::move(message);
75 }
76
82 {
83 return this->encoded_message;
84 }
85
89 inline CompanyID GetErrorOwner() const
90 {
91 return this->owner;
92 }
93
98 inline void AddCost(const Money &cost)
99 {
100 this->cost += cost;
101 }
102
103 void AddCost(CommandCost &&cmd_cost);
104
109 inline void MultiplyCost(int factor)
110 {
111 this->cost *= factor;
112 }
113
118 inline Money GetCost() const
119 {
120 return this->cost;
121 }
122
128 {
129 return this->expense_type;
130 }
131
137 {
138 assert(message != INVALID_STRING_ID);
139 this->success = false;
140 this->message = message;
141 this->extra_message = INVALID_STRING_ID;
142 }
143
149 {
150 if (this->success) return INVALID_STRING_ID;
151 return this->message;
152 }
153
159 {
160 if (this->success) return INVALID_STRING_ID;
161 return this->extra_message;
162 }
163
168 inline bool Succeeded() const
169 {
170 return this->success;
171 }
172
177 inline bool Failed() const
178 {
179 return !this->success;
180 }
181};
182
183CommandCost CommandCostWithParam(StringID str, uint64_t value);
184CommandCost CommandCostWithParam(StringID str, ConvertibleThroughBase auto value) { return CommandCostWithParam(str, value.base()); }
185
196enum class Commands : uint8_t {
199 BuildRail,
200 RemoveRail,
211
214
219
222
227 BuildRoad,
230
232
233 BuildDock,
234
236 BuildBuoy,
237
238 PlantTree,
239
245
249
255
257
263
266
270
273
281
282 PlaceSign,
283 RenameSign,
284 MoveSign,
285
287
288 Pause,
289
290 BuyCompany,
291
292 FoundTown,
293 RenameTown,
294 TownAction,
297 TownRating,
299 ExpandTown,
300 DeleteTown,
301 PlaceHouse,
303
304 OrderRefit,
305 CloneOrder,
306 ClearArea,
307
308 MoneyCheat,
310 BuildCanal,
311
316 CreateGoal,
317 RemoveGoal,
334
335 LevelLand,
336
337 BuildLock,
338
341
342 GiveMoney,
345
347
354
357 AlterGroup,
363
364 MoveOrder,
370
372
378
379 End,
380};
381
387enum class DoCommandFlag : uint8_t {
388 Execute,
389 Auto,
390 QueryCost,
391 NoWater,
393 Bankrupt,
396 AllTiles,
399};
401
407enum class CommandFlag : uint8_t {
408 Server,
409 Spectator,
410 Offline,
411 Auto,
412 AllTiles,
413 NoTest,
414 NoWater,
415 ClientID,
416 Deity,
417 StrCtrl,
418 NoEst,
419 Location,
420};
422
437
440enum class CommandPauseLevel : uint8_t {
441 NoActions,
444 AllActions,
445};
446
447
448template <typename T> struct CommandFunctionTraitHelper;
449template <typename... Targs>
451 using Args = std::tuple<std::decay_t<Targs>...>;
452 using RetTypes = void;
453 using CbArgs = Args;
454 using CbProcType = void(*)(Commands, const CommandCost &);
455};
456template <template <typename...> typename Tret, typename... Tretargs, typename... Targs>
457struct CommandFunctionTraitHelper<Tret<CommandCost, Tretargs...>(*)(DoCommandFlags, Targs...)> {
458 using Args = std::tuple<std::decay_t<Targs>...>;
459 using RetTypes = std::tuple<std::decay_t<Tretargs>...>;
460 using CbArgs = std::tuple<std::decay_t<Tretargs>..., std::decay_t<Targs>...>;
461 using CbProcType = void(*)(Commands, const CommandCost &, Tretargs...);
462};
463
465template <Commands Tcmd> struct CommandTraits;
466
467#define DEF_CMD_TRAIT(cmd_, proc_, flags_, type_) \
468 template <> struct CommandTraits<cmd_> { \
469 using ProcType = decltype(&proc_); \
470 using Args = typename CommandFunctionTraitHelper<ProcType>::Args; \
471 using RetTypes = typename CommandFunctionTraitHelper<ProcType>::RetTypes; \
472 using CbArgs = typename CommandFunctionTraitHelper<ProcType>::CbArgs; \
473 using RetCallbackProc = typename CommandFunctionTraitHelper<ProcType>::CbProcType; \
474 static constexpr Commands cmd = cmd_; \
475 static constexpr auto &proc = proc_; \
476 static constexpr CommandFlags flags = flags_; \
477 static constexpr CommandType type = type_; \
478 static inline constexpr std::string_view name = #proc_; \
479 };
480
482typedef std::vector<uint8_t> CommandDataBuffer;
483
496typedef void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile);
497
512typedef void CommandCallbackData(Commands cmd, const CommandCost &result, const CommandDataBuffer &data, CommandDataBuffer result_data);
513
514#endif /* COMMAND_TYPE_H */
Common return value for all commands.
ExpensesType GetExpensesType() const
The expense type of the cost.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
void MakeError(StringID message)
Makes this CommandCost behave like an error command.
Money cost
The cost of this action.
StringID extra_message
Additional warning message for when success is unset.
CommandCost(ExpensesType ex_t, const Money &cst)
Creates a command return value with the given start cost and expense type.
Money GetCost() const
The costs as made up to this moment.
CommandCost(ExpensesType ex_t)
Creates a command cost with given expense type and start cost of 0.
void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
Owner owner
Originator owner of error.
CommandCost(StringID msg, StringID extra_msg=INVALID_STRING_ID)
Creates a command return value with one, or optionally two, error message strings.
StringID message
Warning message for when success is unset.
bool Failed() const
Did this command fail?
EncodedString & GetEncodedMessage()
Get the last encoded error message.
CommandCost()
Creates a command cost return with no cost and no error.
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
StringID GetErrorMessage() const
Returns the error message of a command.
void SetErrorOwner(Owner owner)
Set the 'owner' (the originator) of this error message.
bool success
Whether the command went fine up to this moment.
CompanyID GetErrorOwner() const
Get the originator owner for this error.
ExpensesType expense_type
the type of expense as shown on the finances view
StringID GetExtraErrorMessage() const
Returns the extra error message of a command.
EncodedString encoded_message
Encoded error message, used if the error message includes parameters.
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
CommandType
Types of commands we have.
@ VehicleConstruction
Construction, modification (incl. refit) and destruction of vehicles.
@ RouteManagement
Modifications to route management (orders, groups, etc).
@ Cheat
A cheat of some sorts.
@ OtherManagement
Renaming stuff, changing company colours, placing signs, etc.
@ LandscapeConstruction
Construction and destruction of objects on the map.
@ MoneyManagement
Management of money, i.e. loans.
@ CompanySetting
Changing settings related to a company.
@ VehicleManagement
Stopping, starting, sending to depot, turning around, replace orders etc.
@ ServerSetting
Pausing/removing companies/server settings.
void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile)
Define a callback function for the client, after the command is finished.
DoCommandFlag
List of flags for a command.
@ Auto
don't allow building on structures
@ QueryCost
query cost only, don't build.
@ NoModifyTownRating
do not change town rating
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
@ AllTiles
allow this command also on TileType::Void tiles
@ NoCargoCapacityCheck
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
@ ForceClearTile
do not only remove the object on the tile, but also clear any water left on it
@ AutoReplace
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
@ NoTestTownRating
town rating does not disallow you from building
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:417
CommandFlag
Command flags for the command table _command_proc_table.
@ NoEst
the command is never estimated.
@ Deity
the command may be executed by COMPANY_DEITY
@ Spectator
the command may be initiated by a spectator
@ Offline
the command cannot be executed in a multiplayer game; single-player only
@ Server
the command can only be initiated by the server
@ ClientID
set p2 with the ClientID of the sending client.
@ StrCtrl
the command's string may contain control strings
@ Location
the command has implicit location argument.
@ NoTest
the command's output may differ between test and execute due to town rating changes etc.
CommandPauseLevel
Different command pause levels.
@ NoLandscaping
No landscaping actions may be executed.
@ NoConstruction
No construction actions may be executed.
@ NoActions
No user actions may be executed.
@ AllActions
All actions may be executed.
void CommandCallbackData(Commands cmd, const CommandCost &result, const CommandDataBuffer &data, CommandDataBuffer result_data)
Define a callback function for the client, after the command is finished.
std::vector< uint8_t > CommandDataBuffer
Storage buffer for serialized command data.
Commands
List of commands.
@ RenameDepot
rename a depot
@ ForceTrainProceed
proceed a train to pass a red signal
@ ClearArea
clear an area
@ TownGrowthRate
set the town growth rate
@ SetStoryPageTitle
update title of a story page
@ ChangeTimetable
change the timetable for a vehicle
@ BuildRailWaypoint
build a waypoint
@ SendVehicleToDepot
send a vehicle to a depot
@ PlaceHouseArea
place an area of houses
@ TownCargoGoal
set the goal of a cargo for a town
@ MoveOrder
move an order
@ Pause
pause the game
@ BuildObject
build an object
@ IndustrySetProduction
change industry production
@ CreateGoal
create a new goal
@ DepotMassAutoreplace
force the autoreplace to take action in a given depot
@ MoveSign
move a sign
@ AutofillTimetable
autofill the timetable
@ RemoveGoal
remove a goal
@ CloneOrder
clone (and share) an order
@ BuildAirport
build an airport
@ ChangeServiceInterval
change the server interval of a vehicle
@ MoveStationName
move a station name
@ SetTimetableStart
set the date that a timetable should start
@ WantEnginePreview
confirm the preview of an engine
@ PlantTree
plant a tree
@ DecreaseLoan
decrease the loan from the bank
@ GoalQuestion
ask a goal related question
@ BuildRoadDepot
build a road depot
@ PlaceSign
place a sign
@ SetCompanyManagerFace
set the manager's face of the company
@ OrderRefit
change the refit information of an order (for "goto depot" )
@ ShowStoryPage
show a story page
@ SetGroupLivery
set the livery for a group
@ ScrollViewport
scroll main viewport of players
@ SetGoalDestination
update goal destination of a goal
@ BuildSignal
build a signal
@ IndustrySetText
change additional text for the industry
@ ChangeTimetableBulk
change the timetable for all orders of a vehicle
@ IndustrySetFlags
change industry control flags
@ UpdateLeagueTableElementData
update the data fields of a league table element
@ ConvertRoad
convert a road type
@ UpdateLeagueTableElementScore
update the score of a league table element
@ RenameStation
rename a station
@ RemoveRoadLong
remove a complete road (not a "half" one)
@ MoneyCheat
do the money cheat
@ ConvertRail
convert a rail type
@ ClearOrderBackup
clear the order backup of a given user/tile
@ ChangeSetting
change a setting
@ SellVehicle
sell a vehicle
@ GoalQuestionAnswer
answer(s) to Commands::GoalQuestion
@ CompanyControl
used in multiplayer to create a new companies etc.
@ ExpandTown
expand a town
@ AlterGroup
alter a group
@ EngineControl
control availability of the engine for companies
@ BuildIndustry
build a new industry
@ BuildCanal
build a canal
@ DeleteTown
delete a town
@ SetStoryPageDate
update date of a story page
@ FoundTown
found a town
@ BuildTunnel
build a tunnel
@ SetCompanyColour
set the colour of the company
@ BuildRoadWaypoint
build a road waypoint
@ ReverseTrainDirection
turn a train around
@ IncreaseLoan
increase the loan from the bank
@ BuildBridge
build a bridge
@ SetVehicleVisibility
hide or unhide a vehicle in the build vehicle and autoreplace GUIs
@ AutoreplaceVehicle
replace/renew a vehicle while it is in a depot
@ BuildObjectArea
build an area of objects
@ CreateCustomNewsItem
create a custom news message
@ CreateLeagueTable
create a new league table
@ AddSharedVehiclesToGroup
add all other shared vehicles to a group which are missing
@ InsertOrder
insert a new order
@ PlaceHouse
place a house
@ RenameCompany
change the company name
@ SetGoalText
update goal text of a goal
@ BuildShipDepot
build a ship depot
@ TownAction
do a action from the town detail window (like advertises or bribe)
@ BuildVehicle
build a vehicle
@ UpdateStoryPageElement
update a story page element
@ BuyCompany
buy a company which is bankrupt
@ BuildDock
build a dock
@ CloneVehicle
clone a vehicle
@ BuildRailStation
build a rail station
@ BuildRailDepot
build a train depot
@ TownSetText
set the custom text of a town
@ RemoveFromRailStation
remove a (rectangle of) tiles from a rail station
@ SetGoalProgress
update goal progress text of a goal
@ MassStartStop
start/stop all vehicles (in a depot)
@ CreateLeagueTableElement
create a new element in a league table
@ RefitVehicle
refit the cargo space of a vehicle
@ DepotMassSell
sell all vehicles which are in a given depot
@ RenameEngine
rename a engine (in the engine list)
@ IndustrySetExclusivity
change industry exclusive consumer/supplier
@ OpenCloseAirport
open/close an airport to incoming aircraft
@ StoryPageButton
selection via story page button
@ TerraformLand
terraform a tile
@ MoveRailVehicle
move a rail vehicle (in the depot)
@ BuildRail
build a single rail track
@ RemoveLeagueTableElement
remove a league table element
@ BuildBuoy
build a buoy
@ RemoveFromRoadWaypoint
remove a (rectangle of) tiles from a road waypoint
@ RenamePresident
change the president name
@ RemoveAllVehiclesGroup
remove all vehicles from a group
@ SetGroupFlag
set/clear a flag for a group
@ ChangeBankBalance
change bank balance to charge costs or give money from a GS
@ TurnRoadVehicle
turn a road vehicle around
@ SetVehicleOnTime
set the vehicle on time feature (timetable)
@ BuildRailLong
build a rail track
@ RemoveStoryPage
remove a story page
@ SetCompanyMaxLoan
sets the max loan for the company
@ RemoveRoadStop
remove a road stop
@ AddVehicleToGroup
add a vehicle to a group
@ BuildRoad
build a "half" road
@ TownRating
set rating of a company in a town
@ RemoveSignal
remove a signal
@ MoveWaypointNAme
move a waypoint name
@ RemoveSignalLong
remove signals along a track (by dragging)
@ SetGoalCompleted
update goal completed status of a goal
@ CreateSubsidy
create a new subsidy
@ RemoveRail
remove a single rail track
@ BuildSignalLong
add signals along a track (by dragging)
@ StartStopVehicle
start or stop a vehicle
@ LevelLand
level land
@ RemoveRailLong
remove a rail track
@ CreateStoryPageElement
create a new story page element
@ CreateGroup
create a new group
@ SetAutoreplace
set an autoreplace entry
@ CreateStoryPage
create a new story page
@ DeleteOrder
delete an order
@ RenameTown
rename a town
@ RenameVehicle
rename a whole vehicle
@ DeleteGroup
delete a group
@ RemoveFromRailWaypoint
remove a (rectangle of) tiles from a rail waypoint
@ BuildLock
build a lock
@ GiveMoney
give money to another company
@ ModifyOrder
modify an order (like set full-load)
@ ChangeCompanySetting
change a company setting
@ RenameSign
rename a sign
@ RemoveStoryPageElement
remove a story page element
@ BuildRoadLong
build a complete road (not a "half" one)
@ LandscapeClear
demolish a tile
@ BuildRoadStop
build a road stop
@ RenameWaypoint
rename a waypoint
@ SkipToOrder
skip an order to the next of specific one
@ CompanyAllowListControl
Used in multiplayer to add/remove a client's public key to/from the company's allow list.
Types related to companies.
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
Types related to the economy.
ExpensesType
Types of expenses.
@ INVALID_EXPENSES
Invalid expense type.
Types related to strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Defines the traits of a command.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:115
Types related to tiles.