OpenTTD Source 20260108-master-g8ba1860eaa
command_func.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_FUNC_H
11#define COMMAND_FUNC_H
12
13#include "command_type.h"
15#include "company_type.h"
16#include "company_func.h"
17#include "core/backup_type.hpp"
19#include "tile_map.h"
20
29
30void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data);
32
33bool IsValidCommand(Commands cmd);
35std::string_view GetCommandName(Commands cmd);
37
38template <Commands Tcmd>
40{
42}
43
49static constexpr inline DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
50{
51 DoCommandFlags flags = {};
53 if (cmd_flags.Test(CommandFlag::Auto)) flags.Set(DoCommandFlag::Auto);
55 return flags;
56}
57
60 RecursiveCommandCounter() noexcept { _counter++; }
61 ~RecursiveCommandCounter() noexcept { _counter--; }
62
64 bool IsTopLevel() const { return _counter == 1; }
65private:
66 static int _counter;
67};
68
69#if defined(__GNUC__) && !defined(__clang__)
70/*
71 * We cast specialized function pointers to a generic one, but don't use the
72 * converted value to call the function, which is safe, except that GCC
73 * helpfully thinks it is not.
74 *
75 * "Any pointer to function can be converted to a pointer to a different function type.
76 * Calling the function through a pointer to a different function type is undefined,
77 * but converting such pointer back to pointer to the original function type yields
78 * the pointer to the original function." */
79# pragma GCC diagnostic push
80# pragma GCC diagnostic ignored "-Wcast-function-type"
81# define SILENCE_GCC_FUNCTION_POINTER_CAST
82#endif
83
84template <Commands TCmd, typename T, bool THasTile> struct CommandHelper;
85
87protected:
88 static void InternalDoBefore(bool top_level, bool test);
89 static void InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test);
90 static std::tuple<bool, bool, bool> InternalPostBefore(Commands cmd, CommandFlags flags, TileIndex tile, StringID err_message, bool network_command);
91 static void InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd);
92 static bool InternalExecutePrepTest(CommandFlags cmd_flags, TileIndex tile, Backup<CompanyID> &cur_company);
93 static std::tuple<bool, bool, bool> InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, Backup<CompanyID> &cur_company);
94 static CommandCost InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company);
95 static void LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed);
96};
97
105template <Commands Tcmd, typename Tret, typename... Targs>
106struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true> : protected CommandHelperBase {
107private:
109 static inline CommandCost &ExtractCommandCost(Tret &ret)
110 {
111 if constexpr (std::is_same_v<Tret, CommandCost>) {
112 return ret;
113 } else {
114 return std::get<0>(ret);
115 }
116 }
117
119 static inline Tret MakeResult(const CommandCost &cost)
120 {
121 Tret ret{};
122 ExtractCommandCost(ret) = cost;
123 return ret;
124 }
125
126public:
140 static Tret Do(DoCommandFlags flags, Targs... args)
141 {
142 if constexpr (std::is_same_v<TileIndex, std::tuple_element_t<0, std::tuple<Targs...>>>) {
143 /* Do not even think about executing out-of-bounds tile-commands. */
144 TileIndex tile = std::get<0>(std::make_tuple(args...));
145 if (tile != 0 && (tile >= Map::Size() || (!IsValidTile(tile) && !flags.Test(DoCommandFlag::AllTiles)))) return MakeResult(CMD_ERROR);
146 }
147
148 RecursiveCommandCounter counter{};
149
150 /* Only execute the test call if it's toplevel, or we're not execing. */
151 if (counter.IsTopLevel() || !flags.Test(DoCommandFlag::Execute)) {
152 InternalDoBefore(counter.IsTopLevel(), true);
154 InternalDoAfter(ExtractCommandCost(res), flags, counter.IsTopLevel(), true); // Can modify res.
155
156 if (ExtractCommandCost(res).Failed() || !flags.Test(DoCommandFlag::Execute)) return res;
157 }
158
159 /* Execute the command here. All cost-relevant functions set the expenses type
160 * themselves to the cost object at some point. */
161 InternalDoBefore(counter.IsTopLevel(), false);
162 Tret res = CommandTraits<Tcmd>::proc(flags, args...);
163 InternalDoAfter(ExtractCommandCost(res), flags, counter.IsTopLevel(), false);
164
165 return res;
166 }
167
173 static inline bool Post(StringID err_message, Targs... args) { return Post<CommandCallback>(err_message, nullptr, std::forward<Targs>(args)...); }
179 template <typename Tcallback>
180 static inline bool Post(Tcallback *callback, Targs... args) { return Post((StringID)0, callback, std::forward<Targs>(args)...); }
185 static inline bool Post(Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, std::forward<Targs>(args)...); }
186
197 template <typename Tcallback>
198 static bool Post(StringID err_message, Tcallback *callback, Targs... args)
199 {
200 assert(::IsNetworkRegisteredCallback(reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback))));
201 return InternalPost(err_message, callback, true, false, std::forward_as_tuple(args...));
202 }
203
212 template <typename Tcallback>
213 static bool PostFromNet(StringID err_message, Tcallback *callback, bool my_cmd, std::tuple<Targs...> args)
214 {
215 return InternalPost(err_message, callback, my_cmd, true, std::move(args));
216 }
217
225 static void SendNet(StringID err_message, CompanyID company, Targs... args)
226 {
227 auto args_tuple = std::forward_as_tuple(args...);
228
229 ::NetworkSendCommand(Tcmd, err_message, nullptr, company, EndianBufferWriter<CommandDataBuffer>::FromValue(args_tuple));
230 }
231
242 template <typename Tcallback>
243 static Tret Unsafe(StringID err_message, Tcallback *callback, bool my_cmd, bool estimate_only, TileIndex location, std::tuple<Targs...> args)
244 {
245 return Execute(err_message, reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback)), my_cmd, estimate_only, false, location, std::move(args));
246 }
247
248protected:
250 template <class T>
251 static inline void SetClientIdHelper([[maybe_unused]] T &data)
252 {
253 if constexpr (std::is_same_v<ClientID, T>) {
254 if (data == INVALID_CLIENT_ID) data = CLIENT_ID_SERVER;
255 }
256 }
257
259 template <class Ttuple, size_t... Tindices>
260 static inline void SetClientIds(Ttuple &values, std::index_sequence<Tindices...>)
261 {
262 ((SetClientIdHelper(std::get<Tindices>(values))), ...);
263 }
264
266 template <template <typename...> typename Tt, typename T1, typename... Ts>
267 static inline Tt<Ts...> RemoveFirstTupleElement(const Tt<T1, Ts...> &tuple)
268 {
269 return std::apply([](auto &&, const auto&... args) { return std::tie(args...); }, tuple);
270 }
271
272 template <typename Tcallback>
273 static bool InternalPost(StringID err_message, Tcallback *callback, bool my_cmd, bool network_command, std::tuple<Targs...> args)
274 {
275 /* Where to show the message? */
276 TileIndex tile{};
277 if constexpr (std::is_same_v<TileIndex, std::tuple_element_t<0, decltype(args)>>) {
278 tile = std::get<0>(args);
279 }
280
281 return InternalPost(err_message, callback, my_cmd, network_command, tile, std::move(args));
282 }
283
284 template <typename Tcallback>
285 static bool InternalPost(StringID err_message, Tcallback *callback, bool my_cmd, bool network_command, TileIndex tile, std::tuple<Targs...> args)
286 {
287 /* Do not even think about executing out-of-bounds tile-commands. */
288 if (tile != 0 && (tile >= Map::Size() || (!IsValidTile(tile) && !GetCommandFlags<Tcmd>().Test(CommandFlag::AllTiles)))) return false;
289
290 auto [err, estimate_only, only_sending] = InternalPostBefore(Tcmd, GetCommandFlags<Tcmd>(), tile, err_message, network_command);
291 if (err) return false;
292
293 /* Only set client IDs when the command does not come from the network. */
294 if (!network_command && GetCommandFlags<Tcmd>().Test(CommandFlag::ClientID)) SetClientIds(args, std::index_sequence_for<Targs...>{});
295
296 Tret res = Execute(err_message, reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback)), my_cmd, estimate_only, network_command, tile, args);
297 InternalPostResult(ExtractCommandCost(res), tile, estimate_only, only_sending, err_message, my_cmd);
298
299 if (!estimate_only && !only_sending && callback != nullptr) {
300 if constexpr (std::is_same_v<Tcallback, CommandCallback>) {
301 /* Callback that doesn't need any command arguments. */
302 callback(Tcmd, ExtractCommandCost(res), tile);
303 } else if constexpr (std::is_same_v<Tcallback, CommandCallbackData>) {
304 /* Generic callback that takes packed arguments as a buffer. */
305 if constexpr (std::is_same_v<Tret, CommandCost>) {
306 callback(Tcmd, ExtractCommandCost(res), EndianBufferWriter<CommandDataBuffer>::FromValue(args), {});
307 } else {
308 callback(Tcmd, ExtractCommandCost(res), EndianBufferWriter<CommandDataBuffer>::FromValue(args), EndianBufferWriter<CommandDataBuffer>::FromValue(RemoveFirstTupleElement(res)));
309 }
310 } else if constexpr (!std::is_same_v<Tret, CommandCost> && std::is_same_v<Tcallback *, typename CommandTraits<Tcmd>::RetCallbackProc>) {
311 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd), res));
312 } else {
313 /* Callback with arguments. We assume that the tile is only interesting if it actually is in the command arguments. */
314 if constexpr (std::is_same_v<Tret, CommandCost>) {
315 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd, res), args));
316 } else {
317 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd), res, args));
318 }
319 }
320 }
321
322 return ExtractCommandCost(res).Succeeded();
323 }
324
326 template <class T>
327 static inline bool ClientIdIsSet([[maybe_unused]] T &data)
328 {
329 if constexpr (std::is_same_v<ClientID, T>) {
330 return data != INVALID_CLIENT_ID;
331 } else {
332 return true;
333 }
334 }
335
337 template <class Ttuple, size_t... Tindices>
338 static inline bool AllClientIdsSet(Ttuple &values, std::index_sequence<Tindices...>)
339 {
340 return (ClientIdIsSet(std::get<Tindices>(values)) && ...);
341 }
342
343 template <class Ttuple>
344 static inline Money ExtractAdditionalMoney([[maybe_unused]] Ttuple &values)
345 {
346 if constexpr (std::is_same_v<std::tuple_element_t<1, Tret>, Money>) {
347 return std::get<1>(values);
348 } else {
349 return {};
350 }
351 }
352
353 static Tret Execute(StringID err_message, CommandCallback *callback, bool, bool estimate_only, bool network_command, TileIndex tile, std::tuple<Targs...> args)
354 {
355 /* Prevent recursion; it gives a mess over the network */
356 RecursiveCommandCounter counter{};
357 assert(counter.IsTopLevel());
358
359 /* Command flags are used internally */
360 constexpr CommandFlags cmd_flags = GetCommandFlags<Tcmd>();
361
362 if constexpr (cmd_flags.Test(CommandFlag::ClientID)) {
363 /* Make sure arguments are properly set to a ClientID also when processing external commands. */
364 assert(AllClientIdsSet(args, std::index_sequence_for<Targs...>{}));
365 }
366
368 if (!InternalExecutePrepTest(cmd_flags, tile, cur_company)) {
369 cur_company.Trash();
370 return MakeResult(CMD_ERROR);
371 }
372
373 /* Test the command. */
374 DoCommandFlags flags = CommandFlagsToDCFlags(cmd_flags);
375 Tret res = std::apply(CommandTraits<Tcmd>::proc, std::tuple_cat(std::make_tuple(flags), args));
376
377 auto [exit_test, desync_log, send_net] = InternalExecuteValidateTestAndPrepExec(ExtractCommandCost(res), cmd_flags, estimate_only, network_command, cur_company);
378 if (exit_test) {
379 if (desync_log) LogCommandExecution(Tcmd, err_message, EndianBufferWriter<CommandDataBuffer>::FromValue(args), true);
380 cur_company.Restore();
381 return res;
382 }
383
384 /* If we are in network, and the command is not from the network
385 * send it to the command-queue and abort execution. */
386 if (send_net) {
388 cur_company.Restore();
389
390 /* Don't return anything special here; no error, no costs.
391 * This way it's not handled by DoCommand and only the
392 * actual execution of the command causes messages. Also
393 * reset the storages as we've not executed the command. */
394 return {};
395 }
396
397 if (desync_log) LogCommandExecution(Tcmd, err_message, EndianBufferWriter<CommandDataBuffer>::FromValue(args), false);
398
399 /* Actually try and execute the command. */
400 Tret res2 = std::apply(CommandTraits<Tcmd>::proc, std::tuple_cat(std::make_tuple(flags | DoCommandFlag::Execute), args));
401
402 /* Convention: If the second result element is of type Money,
403 * this is the additional cash required for the command. */
404 Money additional_money{};
405 if constexpr (!std::is_same_v<Tret, CommandCost>) { // No short-circuiting for 'if constexpr'.
406 additional_money = ExtractAdditionalMoney(res2);
407 }
408
409 if constexpr (std::is_same_v<Tret, CommandCost>) {
410 return InternalExecuteProcessResult(Tcmd, cmd_flags, res, res2, additional_money, tile, cur_company);
411 } else {
412 std::get<0>(res2) = InternalExecuteProcessResult(Tcmd, cmd_flags, ExtractCommandCost(res), ExtractCommandCost(res2), additional_money, tile, cur_company);
413 return res2;
414 }
415 }
416};
417
425template <Commands Tcmd, typename Tret, typename... Targs>
426struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), false> : CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true>
427{
428 /* Do not allow Post without explicit location. */
429 static inline bool Post(StringID err_message, Targs... args) = delete;
430 template <typename Tcallback>
431 static inline bool Post(Tcallback *callback, Targs... args) = delete;
432 static inline bool Post(Targs... args) = delete;
433 template <typename Tcallback>
434 static bool Post(StringID err_message, Tcallback *callback, Targs... args) = delete;
435
442 static inline bool Post(StringID err_message, TileIndex location, Targs... args) { return Post<CommandCallback>(err_message, nullptr, location, std::forward<Targs>(args)...); }
449 template <typename Tcallback>
450 static inline bool Post(Tcallback *callback, TileIndex location, Targs... args) { return Post((StringID)0, callback, location, std::forward<Targs>(args)...); }
456 static inline bool Post(TileIndex location, Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, location, std::forward<Targs>(args)...); }
457
466 template <typename Tcallback>
467 static inline bool Post(StringID err_message, Tcallback *callback, TileIndex location, Targs... args)
468 {
469 return CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true>::InternalPost(err_message, callback, true, false, location, std::forward_as_tuple(args...));
470 }
471};
472
473#ifdef SILENCE_GCC_FUNCTION_POINTER_CAST
474# pragma GCC diagnostic pop
475#endif
476
477template <Commands Tcmd>
479
480#endif /* COMMAND_FUNC_H */
Class for backupping variables and making sure they are restored later.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
Common return value for all commands.
static std::tuple< bool, bool, bool > InternalPostBefore(Commands cmd, CommandFlags flags, TileIndex tile, StringID err_message, bool network_command)
Decide what to do with the command depending on current game state.
Definition command.cpp:207
static void InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd)
Process result of executing a command, possibly displaying any error to the player.
Definition command.cpp:238
static void InternalDoBefore(bool top_level, bool test)
Prepare for calling a command proc.
Definition command.cpp:169
static void LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed)
Helper to make a desync log for a command.
Definition command.cpp:261
static CommandCost InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup< CompanyID > &cur_company)
Process the result of a command test run and execution run.
Definition command.cpp:342
static void InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test)
Process result after calling a command proc.
Definition command.cpp:182
static std::tuple< bool, bool, bool > InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, Backup< CompanyID > &cur_company)
Validate result of test run and prepare for real execution.
Definition command.cpp:302
static bool InternalExecutePrepTest(CommandFlags cmd_flags, TileIndex tile, Backup< CompanyID > &cur_company)
Prepare for the test run of a command proc call.
Definition command.cpp:272
Endian-aware buffer adapter that always writes values in little endian order.
CommandFlags GetCommandFlags(Commands cmd)
This function mask the parameter with CMD_ID_MASK and returns the flags which belongs to the given co...
Definition command.cpp:118
bool IsCommandAllowedWhilePaused(Commands cmd)
Returns whether the command is allowed while the game is paused.
Definition command.cpp:144
static constexpr DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
bool IsNetworkRegisteredCallback(CommandCallback *callback)
Helper function to ensure that callbacks used when Posting commands are actually registered for the n...
std::string_view GetCommandName(Commands cmd)
This function mask the parameter with CMD_ID_MASK and returns the name which belongs to the given com...
Definition command.cpp:132
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
bool IsValidCommand(Commands cmd)
This function range-checks a cmd.
Definition command.cpp:106
void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data)
Prepare a DoCommand to be send over the network.
Types related to commands.
void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile)
Define a callback function for the client, after the command is finished.
@ Auto
don't allow building on structures
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ AllTiles
allow this command also on MP_VOID tiles
@ Auto
set the DoCommandFlag::Auto flag on this command
@ NoWater
set the DoCommandFlag::NoWater flag on this command
@ AllTiles
allow this command also on MP_VOID tiles
@ ClientID
set p2 with the ClientID of the sending client.
@ Location
the command has implicit location argument.
std::vector< uint8_t > CommandDataBuffer
Storage buffer for serialized command data.
Commands
List of commands.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
Types related to companies.
Endian-aware buffer.
static void SetClientIds(Ttuple &values, ClientID client_id, std::index_sequence< Tindices... >)
Set all invalid ClientID's to the proper value.
static void SetClientIdHelper(T &data, ClientID client_id)
Helper to process a single ClientID argument.
Types used for networking.
@ INVALID_CLIENT_ID
Client is not part of anything.
@ CLIENT_ID_SERVER
Servers always have this ID.
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)
Class to backup a specific variable and restore it later.
static bool Post(TileIndex location, Targs... args)
Shortcut for Post when not using a callback or an error message.
static bool Post(StringID err_message, Tcallback *callback, TileIndex location, Targs... args)
Post variant that takes a TileIndex (for error window location and text effects) for commands that do...
static bool Post(StringID err_message, TileIndex location, Targs... args)
Shortcut for Post when not using a callback.
static bool Post(Tcallback *callback, TileIndex location, Targs... args)
Shortcut for Post when not using an error message.
static bool Post(StringID err_message, Tcallback *callback, Targs... args)
Top-level network safe command execution for the current company.
static Tret Do(DoCommandFlags flags, Targs... args)
This function executes a given command with the parameters from the #CommandProc parameter list.
static bool ClientIdIsSet(T &data)
Helper to process a single ClientID argument.
static bool Post(StringID err_message, Targs... args)
Shortcut for the long Post when not using a callback.
static void SetClientIdHelper(T &data)
Helper to process a single ClientID argument.
static bool PostFromNet(StringID err_message, Tcallback *callback, bool my_cmd, std::tuple< Targs... > args)
Execute a command coming from the network.
static Tret Unsafe(StringID err_message, Tcallback *callback, bool my_cmd, bool estimate_only, TileIndex location, std::tuple< Targs... > args)
Top-level network safe command execution without safety checks.
static void SendNet(StringID err_message, CompanyID company, Targs... args)
Prepare a command to be send over the network.
static bool Post(Tcallback *callback, Targs... args)
Shortcut for the long Post when not using an error message.
static Tt< Ts... > RemoveFirstTupleElement(const Tt< T1, Ts... > &tuple)
Remove the first element of a tuple.
static Tret MakeResult(const CommandCost &cost)
Make a command proc result from a CommandCost.
static bool Post(Targs... args)
Shortcut for the long Post when not using a callback or an error message.
static bool AllClientIdsSet(Ttuple &values, std::index_sequence< Tindices... >)
Check if all ClientID arguments are set to valid values.
static CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static void SetClientIds(Ttuple &values, std::index_sequence< Tindices... >)
Set all invalid ClientID's to the proper value.
Defines the traits of a command.
static uint Size()
Get the size of the map.
Definition map_func.h:290
Helper class to keep track of command nesting level.
bool IsTopLevel() const
Are we in the top-level command execution?
Map writing/reading functions for tiles.
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:87