1 /* $Id: console_cmds.cpp 26000 2013-11-14 22:50:16Z zuu $ */
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/>.
10 /** @file console_cmds.cpp Implementation of the console hooks. */
13 #include "console_internal.h"
15 #include "engine_func.h"
16 #include "landscape.h"
17 #include "saveload/saveload.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "network/network_base.h"
21 #include "network/network_admin.h"
22 #include "network/network_client.h"
23 #include "command_func.h"
24 #include "settings_func.h"
26 #include "fileio_func.h"
27 #include "screenshot.h"
29 #include "strings_func.h"
30 #include "viewport_func.h"
31 #include "window_func.h"
32 #include "date_func.h"
33 #include "company_func.h"
36 #include "ai/ai_config.hpp"
38 #include "console_func.h"
39 #include "engine_base.h"
40 #include "game/game.hpp"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 /* scriptfile handling */
46 static bool _script_running
; ///< Script is running (used to abort execution when #ConReturn is encountered).
48 /** File list storage for the console, for caching the last 'ls' command. */
49 class ConsoleFileList
: public FileList
{
51 ConsoleFileList() : FileList()
53 this->file_list_valid
= false;
56 /** Declare the file storage cache as being invalid, also clears all stored files. */
57 void InvalidateFileList()
60 this->file_list_valid
= false;
64 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
65 * @param Always reload the file storage cache.
67 void ValidateFileList(bool force_reload
= false)
69 if (force_reload
|| !this->file_list_valid
) {
70 this->BuildFileList(FT_SAVEGAME
, SLO_LOAD
);
71 this->file_list_valid
= true;
75 bool file_list_valid
; ///< If set, the file list is valid.
78 static ConsoleFileList _console_file_list
; ///< File storage cache for the console.
80 /* console command defines */
81 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
82 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
92 * Check network availability and inform in console about failure of detection.
93 * @return Network availability.
95 static inline bool NetworkAvailable(bool echo
)
97 if (!_network_available
) {
98 if (echo
) IConsoleError("You cannot use this command because there is no network available.");
105 * Check whether we are a server.
106 * @return Are we a server? True when yes, false otherwise.
108 DEF_CONSOLE_HOOK(ConHookServerOnly
)
110 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
112 if (!_network_server
) {
113 if (echo
) IConsoleError("This command is only available to a network server.");
120 * Check whether we are a client in a network game.
121 * @return Are we a client in a network game? True when yes, false otherwise.
123 DEF_CONSOLE_HOOK(ConHookClientOnly
)
125 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
127 if (_network_server
) {
128 if (echo
) IConsoleError("This command is not available to a network server.");
135 * Check whether we are in a multiplayer game.
136 * @return True when we are client or server in a network game.
138 DEF_CONSOLE_HOOK(ConHookNeedNetwork
)
140 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
142 if (!_networking
|| (!_network_server
&& !MyClient::IsConnected())) {
143 if (echo
) IConsoleError("Not connected. This command is only available in multiplayer.");
150 * Check whether we are in single player mode.
151 * @return True when no network is active.
153 DEF_CONSOLE_HOOK(ConHookNoNetwork
)
156 if (echo
) IConsoleError("This command is forbidden in multiplayer.");
163 # define ConHookNoNetwork NULL
164 #endif /* ENABLE_NETWORK */
166 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool
)
168 if (_settings_client
.gui
.newgrf_developer_tools
) {
169 if (_game_mode
== GM_MENU
) {
170 if (echo
) IConsoleError("This command is only available in game and editor.");
173 #ifdef ENABLE_NETWORK
174 return ConHookNoNetwork(echo
);
183 * Show help for the console.
184 * @param str String to print in the console.
186 static void IConsoleHelp(const char *str
)
188 IConsolePrintF(CC_WARNING
, "- %s", str
);
192 * Reset status of all engines.
193 * @return Will always succeed.
195 DEF_CONSOLE_CMD(ConResetEngines
)
198 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
207 * Reset status of the engine pool.
208 * @return Will always return true.
209 * @note Resetting the pool only succeeds when there are no vehicles ingame.
211 DEF_CONSOLE_CMD(ConResetEnginePool
)
214 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
218 if (_game_mode
== GM_MENU
) {
219 IConsoleError("This command is only available in game and editor.");
223 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
224 IConsoleError("This can only be done when there are no vehicles in the game.");
231 DEF_CONSOLE_CMD(ConCheckCaches
)
234 IConsoleHelp("Debug: Check caches");
238 if (argc
> 2) return false;
240 bool broadcast
= (argc
== 2 && atoi(argv
[1]) > 0 && (!_networking
|| _network_server
));
242 DoCommandP(0, 0, 0, CMD_DESYNC_CHECK
);
244 extern void CheckCaches(bool force_check
);
253 * Reset a tile to bare land in debug mode.
255 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
257 DEF_CONSOLE_CMD(ConResetTile
)
260 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
261 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
267 if (GetArgumentInteger(&result
, argv
[1])) {
268 DoClearSquare((TileIndex
)result
);
278 * Scroll to a tile on the map.
279 * @param arg1 tile tile number or tile x coordinate.
280 * @param arg2 optionally tile y coordinate.
281 * @note When only one argument is given it is intepreted as the tile number.
282 * When two arguments are given, they are interpreted as the tile's x
284 * @return True when either console help was shown or a proper amount of parameters given.
286 DEF_CONSOLE_CMD(ConScrollToTile
)
290 IConsoleHelp("Center the screen on a given tile.");
291 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
292 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
297 if (GetArgumentInteger(&result
, argv
[1])) {
298 if (result
>= MapSize()) {
299 IConsolePrint(CC_ERROR
, "Tile does not exist");
302 ScrollMainWindowToTile((TileIndex
)result
);
310 if (GetArgumentInteger(&x
, argv
[1]) && GetArgumentInteger(&y
, argv
[2])) {
311 if (x
>= MapSizeX() || y
>= MapSizeY()) {
312 IConsolePrint(CC_ERROR
, "Tile does not exist");
315 ScrollMainWindowToTile(TileXY(x
, y
));
326 * Save the map to a file.
327 * @param filename the filename to save the map to.
328 * @return True when help was displayed or the file attempted to be saved.
330 DEF_CONSOLE_CMD(ConSave
)
333 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
338 char *filename
= str_fmt("%s.sav", argv
[1]);
339 IConsolePrint(CC_DEFAULT
, "Saving map...");
341 if (SaveOrLoad(filename
, SLO_SAVE
, DFT_GAME_FILE
, SAVE_DIR
) != SL_OK
) {
342 IConsolePrint(CC_ERROR
, "Saving map failed");
344 IConsolePrintF(CC_DEFAULT
, "Map successfully saved to %s", filename
);
354 * Explicitly save the configuration.
357 DEF_CONSOLE_CMD(ConSaveConfig
)
360 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
361 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
366 IConsolePrint(CC_DEFAULT
, "Saved config.");
370 DEF_CONSOLE_CMD(ConLoad
)
373 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
377 if (argc
!= 2) return false;
379 const char *file
= argv
[1];
380 _console_file_list
.ValidateFileList();
381 const FiosItem
*item
= _console_file_list
.FindItem(file
);
383 if (GetAbstractFileType(item
->type
) == FT_SAVEGAME
) {
384 _switch_mode
= SM_LOAD_GAME
;
385 _file_to_saveload
.SetMode(item
->type
);
386 _file_to_saveload
.SetName(FiosBrowseTo(item
));
387 _file_to_saveload
.SetTitle(item
->title
);
389 IConsolePrintF(CC_ERROR
, "%s: Not a savegame.", file
);
392 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
399 DEF_CONSOLE_CMD(ConRemove
)
402 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
406 if (argc
!= 2) return false;
408 const char *file
= argv
[1];
409 _console_file_list
.ValidateFileList();
410 const FiosItem
*item
= _console_file_list
.FindItem(file
);
412 if (!FiosDelete(item
->name
)) {
413 IConsolePrintF(CC_ERROR
, "%s: Failed to delete file", file
);
416 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
419 _console_file_list
.InvalidateFileList();
424 /* List all the files in the current dir via console */
425 DEF_CONSOLE_CMD(ConListFiles
)
428 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
432 _console_file_list
.ValidateFileList(true);
433 for (uint i
= 0; i
< _console_file_list
.Length(); i
++) {
434 IConsolePrintF(CC_DEFAULT
, "%d) %s", i
, _console_file_list
[i
].title
);
440 /* Change the dir via console */
441 DEF_CONSOLE_CMD(ConChangeDirectory
)
444 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
448 if (argc
!= 2) return false;
450 const char *file
= argv
[1];
451 _console_file_list
.ValidateFileList(true);
452 const FiosItem
*item
= _console_file_list
.FindItem(file
);
454 switch (item
->type
) {
455 case FIOS_TYPE_DIR
: case FIOS_TYPE_DRIVE
: case FIOS_TYPE_PARENT
:
458 default: IConsolePrintF(CC_ERROR
, "%s: Not a directory.", file
);
461 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
464 _console_file_list
.InvalidateFileList();
468 DEF_CONSOLE_CMD(ConPrintWorkingDirectory
)
473 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
477 /* XXX - Workaround for broken file handling */
478 _console_file_list
.ValidateFileList(true);
479 _console_file_list
.InvalidateFileList();
481 FiosGetDescText(&path
, NULL
);
482 IConsolePrint(CC_DEFAULT
, path
);
486 DEF_CONSOLE_CMD(ConClearBuffer
)
489 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
493 IConsoleClearBuffer();
494 SetWindowDirty(WC_CONSOLE
, 0);
499 /**********************************
500 * Network Core Console Commands
501 **********************************/
502 #ifdef ENABLE_NETWORK
504 static bool ConKickOrBan(const char *argv
, bool ban
)
508 if (strchr(argv
, '.') == NULL
&& strchr(argv
, ':') == NULL
) { // banning with ID
509 ClientID client_id
= (ClientID
)atoi(argv
);
511 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
512 * kicking frees closes and subsequently free the connection related instances, which we
513 * would be reading from and writing to after returning. So we would read or write data
514 * from freed memory up till the segfault triggers. */
515 if (client_id
== CLIENT_ID_SERVER
|| client_id
== _redirect_console_to_client
) {
516 IConsolePrintF(CC_ERROR
, "ERROR: Silly boy, you can not %s yourself!", ban
? "ban" : "kick");
520 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
522 IConsoleError("Invalid client");
527 /* Kick only this client, not all clients with that IP */
528 NetworkServerKickClient(client_id
);
532 /* When banning, kick+ban all clients with that IP */
533 n
= NetworkServerKickOrBanIP(client_id
, ban
);
535 n
= NetworkServerKickOrBanIP(argv
, ban
);
539 IConsolePrint(CC_DEFAULT
, ban
? "Client not online, address added to banlist" : "Client not found");
541 IConsolePrintF(CC_DEFAULT
, "%sed %u client(s)", ban
? "Bann" : "Kick", n
);
547 DEF_CONSOLE_CMD(ConKick
)
550 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
551 IConsoleHelp("For client-id's, see the command 'clients'");
555 if (argc
!= 2) return false;
557 return ConKickOrBan(argv
[1], false);
560 DEF_CONSOLE_CMD(ConBan
)
563 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
564 IConsoleHelp("For client-id's, see the command 'clients'");
565 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
569 if (argc
!= 2) return false;
571 return ConKickOrBan(argv
[1], true);
574 DEF_CONSOLE_CMD(ConUnBan
)
577 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | banlist-index>'");
578 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
582 if (argc
!= 2) return false;
586 for (index
= 0; index
< _network_ban_list
.Length(); index
++) {
587 if (strcmp(_network_ban_list
[index
], argv
[1]) == 0) break;
591 if (index
>= _network_ban_list
.Length()) {
592 index
= atoi(argv
[1]) - 1U; // let it wrap
595 if (index
< _network_ban_list
.Length()) {
597 seprintf(msg
, lastof(msg
), "Unbanned %s", _network_ban_list
[index
]);
598 IConsolePrint(CC_DEFAULT
, msg
);
599 free(_network_ban_list
[index
]);
600 _network_ban_list
.Erase(_network_ban_list
.Get(index
));
602 IConsolePrint(CC_DEFAULT
, "Invalid list index or IP not in ban-list.");
603 IConsolePrint(CC_DEFAULT
, "For a list of banned IP's, see the command 'banlist'");
609 DEF_CONSOLE_CMD(ConBanList
)
612 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
616 IConsolePrint(CC_DEFAULT
, "Banlist: ");
619 for (char **iter
= _network_ban_list
.Begin(); iter
!= _network_ban_list
.End(); iter
++, i
++) {
620 IConsolePrintF(CC_DEFAULT
, " %d) %s", i
, *iter
);
626 DEF_CONSOLE_CMD(ConPauseGame
)
629 IConsoleHelp("Pause a network game. Usage: 'pause'");
633 if ((_pause_mode
& PM_PAUSED_NORMAL
) == PM_UNPAUSED
) {
634 DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
635 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game paused.");
637 IConsolePrint(CC_DEFAULT
, "Game is already paused.");
643 DEF_CONSOLE_CMD(ConUnpauseGame
)
646 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
650 if ((_pause_mode
& PM_PAUSED_NORMAL
) != PM_UNPAUSED
) {
651 DoCommandP(0, PM_PAUSED_NORMAL
, 0, CMD_PAUSE
);
652 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game unpaused.");
653 } else if ((_pause_mode
& PM_PAUSED_ERROR
) != PM_UNPAUSED
) {
654 IConsolePrint(CC_DEFAULT
, "Game is in error state and cannot be unpaused via console.");
655 } else if (_pause_mode
!= PM_UNPAUSED
) {
656 IConsolePrint(CC_DEFAULT
, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
658 IConsolePrint(CC_DEFAULT
, "Game is already unpaused.");
664 DEF_CONSOLE_CMD(ConRcon
)
667 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
668 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
672 if (argc
< 3) return false;
674 if (_network_server
) {
675 IConsoleCmdExec(argv
[2]);
677 NetworkClientSendRcon(argv
[1], argv
[2]);
682 DEF_CONSOLE_CMD(ConStatus
)
685 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
689 NetworkServerShowStatusToConsole();
693 DEF_CONSOLE_CMD(ConServerInfo
)
696 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
697 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
701 IConsolePrintF(CC_DEFAULT
, "Current/maximum clients: %2d/%2d", _network_game_info
.clients_on
, _settings_client
.network
.max_clients
);
702 IConsolePrintF(CC_DEFAULT
, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client
.network
.max_companies
);
703 IConsolePrintF(CC_DEFAULT
, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client
.network
.max_spectators
);
708 DEF_CONSOLE_CMD(ConClientNickChange
)
711 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
712 IConsoleHelp("For client-id's, see the command 'clients'");
716 ClientID client_id
= (ClientID
)atoi(argv
[1]);
718 if (client_id
== CLIENT_ID_SERVER
) {
719 IConsoleError("Please use the command 'name' to change your own name!");
723 if (NetworkClientInfo::GetByClientID(client_id
) == NULL
) {
724 IConsoleError("Invalid client");
728 if (!NetworkServerChangeClientName(client_id
, argv
[2])) {
729 IConsoleError("Cannot give a client a duplicate name");
735 DEF_CONSOLE_CMD(ConJoinCompany
)
738 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
739 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
743 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) <= MAX_COMPANIES
? atoi(argv
[1]) - 1 : atoi(argv
[1]));
745 /* Check we have a valid company id! */
746 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
747 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
751 if (NetworkClientInfo::GetByClientID(_network_own_client_id
)->client_playas
== company_id
) {
752 IConsoleError("You are already there!");
756 if (company_id
== COMPANY_SPECTATOR
&& NetworkMaxSpectatorsReached()) {
757 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
761 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
762 IConsoleError("Cannot join AI company.");
766 /* Check if the company requires a password */
767 if (NetworkCompanyIsPassworded(company_id
) && argc
< 3) {
768 IConsolePrintF(CC_ERROR
, "Company %d requires a password to join.", company_id
+ 1);
772 /* non-dedicated server may just do the move! */
773 if (_network_server
) {
774 NetworkServerDoMove(CLIENT_ID_SERVER
, company_id
);
776 NetworkClientRequestMove(company_id
, NetworkCompanyIsPassworded(company_id
) ? argv
[2] : "");
782 DEF_CONSOLE_CMD(ConMoveClient
)
785 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
786 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
790 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID((ClientID
)atoi(argv
[1]));
791 CompanyID company_id
= (CompanyID
)(atoi(argv
[2]) <= MAX_COMPANIES
? atoi(argv
[2]) - 1 : atoi(argv
[2]));
793 /* check the client exists */
795 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
799 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
800 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
804 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
805 IConsoleError("You cannot move clients to AI companies.");
809 if (ci
->client_id
== CLIENT_ID_SERVER
&& _network_dedicated
) {
810 IConsoleError("Silly boy, you cannot move the server!");
814 if (ci
->client_playas
== company_id
) {
815 IConsoleError("You cannot move someone to where he/she already is!");
819 /* we are the server, so force the update */
820 NetworkServerDoMove(ci
->client_id
, company_id
);
825 DEF_CONSOLE_CMD(ConResetCompany
)
828 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
829 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
833 if (argc
!= 2) return false;
835 CompanyID index
= (CompanyID
)(atoi(argv
[1]) - 1);
837 /* Check valid range */
838 if (!Company::IsValidID(index
)) {
839 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
843 if (!Company::IsHumanID(index
)) {
844 IConsoleError("Company is owned by an AI.");
848 if (NetworkCompanyHasClients(index
)) {
849 IConsoleError("Cannot remove company: a client is connected to that company.");
852 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
853 if (ci
->client_playas
== index
) {
854 IConsoleError("Cannot remove company: the server is connected to that company.");
858 /* It is safe to remove this company */
859 DoCommandP(0, 2 | index
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
860 IConsolePrint(CC_DEFAULT
, "Company deleted.");
865 DEF_CONSOLE_CMD(ConNetworkClients
)
868 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
872 NetworkPrintClients();
877 DEF_CONSOLE_CMD(ConNetworkReconnect
)
880 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
881 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
882 IConsoleHelp("All others are a certain company with Company 1 being #1");
886 CompanyID playas
= (argc
>= 2) ? (CompanyID
)atoi(argv
[1]) : COMPANY_SPECTATOR
;
888 case 0: playas
= COMPANY_NEW_COMPANY
; break;
889 case COMPANY_SPECTATOR
: /* nothing to do */ break;
891 /* From a user pov 0 is a new company, internally it's different and all
892 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
894 if (playas
< COMPANY_FIRST
|| playas
>= MAX_COMPANIES
) return false;
898 if (StrEmpty(_settings_client
.network
.last_host
)) {
899 IConsolePrint(CC_DEFAULT
, "No server for reconnecting.");
903 /* Don't resolve the address first, just print it directly as it comes from the config file. */
904 IConsolePrintF(CC_DEFAULT
, "Reconnecting to %s:%d...", _settings_client
.network
.last_host
, _settings_client
.network
.last_port
);
906 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), playas
);
910 DEF_CONSOLE_CMD(ConNetworkConnect
)
913 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
914 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
915 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
919 if (argc
< 2) return false;
920 if (_networking
) NetworkDisconnect(); // we are in network-mode, first close it!
922 const char *port
= NULL
;
923 const char *company
= NULL
;
925 /* Default settings: default port and new company */
926 uint16 rport
= NETWORK_DEFAULT_PORT
;
927 CompanyID join_as
= COMPANY_NEW_COMPANY
;
929 ParseConnectionString(&company
, &port
, ip
);
931 IConsolePrintF(CC_DEFAULT
, "Connecting to %s...", ip
);
932 if (company
!= NULL
) {
933 join_as
= (CompanyID
)atoi(company
);
934 IConsolePrintF(CC_DEFAULT
, " company-no: %d", join_as
);
936 /* From a user pov 0 is a new company, internally it's different and all
937 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
938 if (join_as
!= COMPANY_SPECTATOR
) {
939 if (join_as
> MAX_COMPANIES
) return false;
945 IConsolePrintF(CC_DEFAULT
, " port: %s", port
);
948 NetworkClientConnectGame(NetworkAddress(ip
, rport
), join_as
);
953 #endif /* ENABLE_NETWORK */
955 /*********************************
956 * script file console commands
957 *********************************/
959 DEF_CONSOLE_CMD(ConExec
)
962 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
966 if (argc
< 2) return false;
968 FILE *script_file
= FioFOpenFile(argv
[1], "r", BASE_DIR
);
970 if (script_file
== NULL
) {
971 if (argc
== 2 || atoi(argv
[2]) != 0) IConsoleError("script file not found");
975 _script_running
= true;
977 char cmdline
[ICON_CMDLN_SIZE
];
978 while (_script_running
&& fgets(cmdline
, sizeof(cmdline
), script_file
) != NULL
) {
979 /* Remove newline characters from the executing script */
980 for (char *cmdptr
= cmdline
; *cmdptr
!= '\0'; cmdptr
++) {
981 if (*cmdptr
== '\n' || *cmdptr
== '\r') {
986 IConsoleCmdExec(cmdline
);
989 if (ferror(script_file
)) {
990 IConsoleError("Encountered error while trying to read from script file");
993 _script_running
= false;
994 FioFCloseFile(script_file
);
998 DEF_CONSOLE_CMD(ConReturn
)
1001 IConsoleHelp("Stop executing a running script. Usage: 'return'");
1005 _script_running
= false;
1009 /*****************************
1010 * default console commands
1011 ******************************/
1012 extern bool CloseConsoleLogIfActive();
1014 DEF_CONSOLE_CMD(ConScript
)
1016 extern FILE *_iconsole_output_file
;
1019 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
1020 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1024 if (!CloseConsoleLogIfActive()) {
1025 if (argc
< 2) return false;
1027 IConsolePrintF(CC_DEFAULT
, "file output started to: %s", argv
[1]);
1028 _iconsole_output_file
= fopen(argv
[1], "ab");
1029 if (_iconsole_output_file
== NULL
) IConsoleError("could not open file");
1036 DEF_CONSOLE_CMD(ConEcho
)
1039 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1043 if (argc
< 2) return false;
1044 IConsolePrint(CC_DEFAULT
, argv
[1]);
1048 DEF_CONSOLE_CMD(ConEchoC
)
1051 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1055 if (argc
< 3) return false;
1056 IConsolePrint((TextColour
)Clamp(atoi(argv
[1]), TC_BEGIN
, TC_END
- 1), argv
[2]);
1060 DEF_CONSOLE_CMD(ConNewGame
)
1063 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1064 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1068 StartNewGameWithoutGUI((argc
== 2) ? strtoul(argv
[1], NULL
, 10) : GENERATE_NEW_SEED
);
1072 DEF_CONSOLE_CMD(ConRestart
)
1075 IConsoleHelp("Restart game. Usage: 'restart'");
1076 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1077 IConsoleHelp("However:");
1078 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1079 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1083 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1084 _settings_game
.game_creation
.map_x
= MapLogX();
1085 _settings_game
.game_creation
.map_y
= FindFirstBit(MapSizeY());
1086 _switch_mode
= SM_RESTARTGAME
;
1091 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1092 * @param buf The buffer to print.
1093 * @note All newlines are replace by '\0' characters.
1095 static void PrintLineByLine(char *buf
)
1098 /* Print output line by line */
1099 for (char *p2
= buf
; *p2
!= '\0'; p2
++) {
1102 IConsolePrintF(CC_DEFAULT
, "%s", p
);
1108 DEF_CONSOLE_CMD(ConListAILibs
)
1111 AI::GetConsoleLibraryList(buf
, lastof(buf
));
1113 PrintLineByLine(buf
);
1118 DEF_CONSOLE_CMD(ConListAI
)
1121 AI::GetConsoleList(buf
, lastof(buf
));
1123 PrintLineByLine(buf
);
1128 DEF_CONSOLE_CMD(ConListGameLibs
)
1131 Game::GetConsoleLibraryList(buf
, lastof(buf
));
1133 PrintLineByLine(buf
);
1138 DEF_CONSOLE_CMD(ConListGame
)
1141 Game::GetConsoleList(buf
, lastof(buf
));
1143 PrintLineByLine(buf
);
1148 DEF_CONSOLE_CMD(ConStartAI
)
1150 if (argc
== 0 || argc
> 3) {
1151 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1152 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1153 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1157 if (_game_mode
!= GM_NORMAL
) {
1158 IConsoleWarning("AIs can only be managed in a game.");
1162 if (Company::GetNumItems() == CompanyPool::MAX_SIZE
) {
1163 IConsoleWarning("Can't start a new AI (no more free slots).");
1166 if (_networking
&& !_network_server
) {
1167 IConsoleWarning("Only the server can start a new AI.");
1170 if (_networking
&& !_settings_game
.ai
.ai_in_multiplayer
) {
1171 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1172 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1175 if (!AI::CanStartNew()) {
1176 IConsoleWarning("Can't start a new AI.");
1182 /* Find the next free slot */
1183 FOR_ALL_COMPANIES(c
) {
1184 if (c
->index
!= n
) break;
1188 AIConfig
*config
= AIConfig::GetConfig((CompanyID
)n
);
1190 config
->Change(argv
[1], -1, true);
1191 if (!config
->HasScript()) {
1192 IConsoleWarning("Failed to load the specified AI");
1196 config
->StringToSettings(argv
[2]);
1200 /* Start a new AI company */
1201 DoCommandP(0, 1 | INVALID_COMPANY
<< 16, 0, CMD_COMPANY_CTRL
);
1206 DEF_CONSOLE_CMD(ConReloadAI
)
1209 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1210 IConsoleHelp("Reload the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1214 if (_game_mode
!= GM_NORMAL
) {
1215 IConsoleWarning("AIs can only be managed in a game.");
1219 if (_networking
&& !_network_server
) {
1220 IConsoleWarning("Only the server can reload an AI.");
1224 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1225 if (!Company::IsValidID(company_id
)) {
1226 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1230 if (Company::IsHumanID(company_id
)) {
1231 IConsoleWarning("Company is not controlled by an AI.");
1235 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1236 DoCommandP(0, 2 | company_id
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
1237 DoCommandP(0, 1 | company_id
<< 16, 0, CMD_COMPANY_CTRL
);
1238 IConsolePrint(CC_DEFAULT
, "AI reloaded.");
1243 DEF_CONSOLE_CMD(ConStopAI
)
1246 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1247 IConsoleHelp("Stop the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1251 if (_game_mode
!= GM_NORMAL
) {
1252 IConsoleWarning("AIs can only be managed in a game.");
1256 if (_networking
&& !_network_server
) {
1257 IConsoleWarning("Only the server can stop an AI.");
1261 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1262 if (!Company::IsValidID(company_id
)) {
1263 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1267 if (Company::IsHumanID(company_id
) || company_id
== _local_company
) {
1268 IConsoleWarning("Company is not controlled by an AI.");
1272 /* Now kill the company of the AI. */
1273 DoCommandP(0, 2 | company_id
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
1274 IConsolePrint(CC_DEFAULT
, "AI stopped, company deleted.");
1279 DEF_CONSOLE_CMD(ConRescanAI
)
1282 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1286 if (_networking
&& !_network_server
) {
1287 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1296 DEF_CONSOLE_CMD(ConRescanGame
)
1299 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1303 if (_networking
&& !_network_server
) {
1304 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1313 DEF_CONSOLE_CMD(ConRescanNewGRF
)
1316 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1320 ScanNewGRFFiles(NULL
);
1325 DEF_CONSOLE_CMD(ConGetSeed
)
1328 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1329 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1333 IConsolePrintF(CC_DEFAULT
, "Generation Seed: %u", _settings_game
.game_creation
.generation_seed
);
1337 DEF_CONSOLE_CMD(ConGetDate
)
1340 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1345 ConvertDateToYMD(_date
, &ymd
);
1346 IConsolePrintF(CC_DEFAULT
, "Date: %d-%d-%d", ymd
.day
, ymd
.month
+ 1, ymd
.year
);
1351 DEF_CONSOLE_CMD(ConAlias
)
1353 IConsoleAlias
*alias
;
1356 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1360 if (argc
< 3) return false;
1362 alias
= IConsoleAliasGet(argv
[1]);
1363 if (alias
== NULL
) {
1364 IConsoleAliasRegister(argv
[1], argv
[2]);
1366 free(alias
->cmdline
);
1367 alias
->cmdline
= stredup(argv
[2]);
1372 DEF_CONSOLE_CMD(ConScreenShot
)
1375 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1376 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1377 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1378 "screenshots are always drawn without console");
1382 if (argc
> 3) return false;
1384 ScreenshotType type
= SC_VIEWPORT
;
1385 const char *name
= NULL
;
1388 if (strcmp(argv
[1], "big") == 0) {
1389 /* screenshot big [filename] */
1391 if (argc
> 2) name
= argv
[2];
1392 } else if (strcmp(argv
[1], "giant") == 0) {
1393 /* screenshot giant [filename] */
1395 if (argc
> 2) name
= argv
[2];
1396 } else if (strcmp(argv
[1], "no_con") == 0) {
1397 /* screenshot no_con [filename] */
1399 if (argc
> 2) name
= argv
[2];
1400 } else if (argc
== 2) {
1401 /* screenshot filename */
1404 /* screenshot argv[1] argv[2] - invalid */
1409 MakeScreenshot(type
, name
);
1413 DEF_CONSOLE_CMD(ConMinimap
)
1416 IConsoleHelp("Create a flat image of the game minimap. Usage: 'minimap [owner] [file name]'");
1417 IConsoleHelp("'owner' uses the tile owner to colour the minimap image, this is the only mode at present");
1421 const char *name
= NULL
;
1423 if (strcmp(argv
[1], "owner") != 0) {
1432 return MakeScreenshot(SC_MINIMAP
, name
);
1435 DEF_CONSOLE_CMD(ConInfoCmd
)
1438 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1442 if (argc
< 2) return false;
1444 const IConsoleCmd
*cmd
= IConsoleCmdGet(argv
[1]);
1446 IConsoleError("the given command was not found");
1450 IConsolePrintF(CC_DEFAULT
, "command name: %s", cmd
->name
);
1451 IConsolePrintF(CC_DEFAULT
, "command proc: %p", cmd
->proc
);
1453 if (cmd
->hook
!= NULL
) IConsoleWarning("command is hooked");
1458 DEF_CONSOLE_CMD(ConDebugLevel
)
1461 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1462 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1466 if (argc
> 2) return false;
1469 IConsolePrintF(CC_DEFAULT
, "Current debug-level: '%s'", GetDebugString());
1471 SetDebugString(argv
[1]);
1477 DEF_CONSOLE_CMD(ConExit
)
1480 IConsoleHelp("Exit the game. Usage: 'exit'");
1484 if (_game_mode
== GM_NORMAL
&& _settings_client
.gui
.autosave_on_exit
) DoExitSave();
1490 DEF_CONSOLE_CMD(ConPart
)
1493 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1497 if (_game_mode
!= GM_NORMAL
) return false;
1499 _switch_mode
= SM_MENU
;
1503 DEF_CONSOLE_CMD(ConHelp
)
1506 const IConsoleCmd
*cmd
;
1507 const IConsoleAlias
*alias
;
1509 RemoveUnderscores(argv
[1]);
1510 cmd
= IConsoleCmdGet(argv
[1]);
1516 alias
= IConsoleAliasGet(argv
[1]);
1517 if (alias
!= NULL
) {
1518 cmd
= IConsoleCmdGet(alias
->cmdline
);
1523 IConsolePrintF(CC_ERROR
, "ERROR: alias is of special type, please see its execution-line: '%s'", alias
->cmdline
);
1527 IConsoleError("command not found");
1531 IConsolePrint(CC_WARNING
, " ---- OpenTTD Console Help ---- ");
1532 IConsolePrint(CC_DEFAULT
, " - commands: [command to list all commands: list_cmds]");
1533 IConsolePrint(CC_DEFAULT
, " call commands with '<command> <arg2> <arg3>...'");
1534 IConsolePrint(CC_DEFAULT
, " - to assign strings, or use them as arguments, enclose it within quotes");
1535 IConsolePrint(CC_DEFAULT
, " like this: '<command> \"string argument with spaces\"'");
1536 IConsolePrint(CC_DEFAULT
, " - use 'help <command>' to get specific information");
1537 IConsolePrint(CC_DEFAULT
, " - scroll console output with shift + (up | down | pageup | pagedown)");
1538 IConsolePrint(CC_DEFAULT
, " - scroll console input history with the up or down arrows");
1539 IConsolePrint(CC_DEFAULT
, "");
1543 DEF_CONSOLE_CMD(ConListCommands
)
1546 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1550 for (const IConsoleCmd
*cmd
= _iconsole_cmds
; cmd
!= NULL
; cmd
= cmd
->next
) {
1551 if (argv
[1] == NULL
|| strstr(cmd
->name
, argv
[1]) != NULL
) {
1552 if (cmd
->hook
== NULL
|| cmd
->hook(false) != CHR_HIDE
) IConsolePrintF(CC_DEFAULT
, "%s", cmd
->name
);
1559 DEF_CONSOLE_CMD(ConListAliases
)
1562 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1566 for (const IConsoleAlias
*alias
= _iconsole_aliases
; alias
!= NULL
; alias
= alias
->next
) {
1567 if (argv
[1] == NULL
|| strstr(alias
->name
, argv
[1]) != NULL
) {
1568 IConsolePrintF(CC_DEFAULT
, "%s => %s", alias
->name
, alias
->cmdline
);
1575 DEF_CONSOLE_CMD(ConCompanies
)
1578 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1583 FOR_ALL_COMPANIES(c
) {
1584 /* Grab the company name */
1585 char company_name
[512];
1586 SetDParam(0, c
->index
);
1587 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
1589 const char *password_state
= "";
1591 password_state
= "AI";
1593 #ifdef ENABLE_NETWORK
1594 else if (_network_server
) {
1595 password_state
= StrEmpty(_network_company_states
[c
->index
].password
) ? "unprotected" : "protected";
1600 GetString(colour
, STR_COLOUR_DARK_BLUE
+ _company_colours
[c
->index
], lastof(colour
));
1601 IConsolePrintF(CC_INFO
, "#:%d(%s) Company Name: '%s' Year Founded: %d Money: " OTTD_PRINTF64
" Loan: " OTTD_PRINTF64
" Value: " OTTD_PRINTF64
" (T:%d, R:%d, P:%d, S:%d) %s",
1602 c
->index
+ 1, colour
, company_name
,
1603 c
->inaugurated_year
, (int64
)c
->money
, (int64
)c
->current_loan
, (int64
)CalculateCompanyValue(c
),
1604 c
->group_all
[VEH_TRAIN
].num_vehicle
,
1605 c
->group_all
[VEH_ROAD
].num_vehicle
,
1606 c
->group_all
[VEH_AIRCRAFT
].num_vehicle
,
1607 c
->group_all
[VEH_SHIP
].num_vehicle
,
1614 #ifdef ENABLE_NETWORK
1616 DEF_CONSOLE_CMD(ConSay
)
1619 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1623 if (argc
!= 2) return false;
1625 if (!_network_server
) {
1626 NetworkClientSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0 /* param does not matter */, argv
[1]);
1628 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1629 NetworkServerSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0, argv
[1], CLIENT_ID_SERVER
, from_admin
);
1635 DEF_CONSOLE_CMD(ConSayCompany
)
1638 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1639 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1643 if (argc
!= 3) return false;
1645 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1646 if (!Company::IsValidID(company_id
)) {
1647 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1651 if (!_network_server
) {
1652 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2]);
1654 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1655 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2], CLIENT_ID_SERVER
, from_admin
);
1661 DEF_CONSOLE_CMD(ConSayClient
)
1664 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1665 IConsoleHelp("For client-id's, see the command 'clients'");
1669 if (argc
!= 3) return false;
1671 if (!_network_server
) {
1672 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2]);
1674 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1675 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2], CLIENT_ID_SERVER
, from_admin
);
1681 DEF_CONSOLE_CMD(ConCompanyPassword
)
1684 const char *helpmsg
;
1686 if (_network_dedicated
) {
1687 helpmsg
= "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1688 } else if (_network_server
) {
1689 helpmsg
= "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1691 helpmsg
= "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1694 IConsoleHelp(helpmsg
);
1695 IConsoleHelp("Use \"*\" to disable the password.");
1699 CompanyID company_id
;
1700 const char *password
;
1701 const char *errormsg
;
1704 company_id
= _local_company
;
1706 errormsg
= "You have to own a company to make use of this command.";
1707 } else if (argc
== 3 && _network_server
) {
1708 company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1710 errormsg
= "You have to specify the ID of a valid human controlled company.";
1715 if (!Company::IsValidHumanID(company_id
)) {
1716 IConsoleError(errormsg
);
1720 password
= NetworkChangeCompanyPassword(company_id
, password
);
1722 if (StrEmpty(password
)) {
1723 IConsolePrintF(CC_WARNING
, "Company password cleared");
1725 IConsolePrintF(CC_WARNING
, "Company password changed to: %s", password
);
1731 /* Content downloading only is available with ZLIB */
1732 #if defined(WITH_ZLIB)
1733 #include "network/network_content.h"
1735 /** Resolve a string to a content type. */
1736 static ContentType
StringToContentType(const char *str
)
1738 static const char * const inv_lookup
[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1739 for (uint i
= 1 /* there is no type 0 */; i
< lengthof(inv_lookup
); i
++) {
1740 if (strcasecmp(str
, inv_lookup
[i
]) == 0) return (ContentType
)i
;
1742 return CONTENT_TYPE_END
;
1745 /** Asynchronous callback */
1746 struct ConsoleContentCallback
: public ContentCallback
{
1747 void OnConnect(bool success
)
1749 IConsolePrintF(CC_DEFAULT
, "Content server connection %s", success
? "established" : "failed");
1754 IConsolePrintF(CC_DEFAULT
, "Content server connection closed");
1757 void OnDownloadComplete(ContentID cid
)
1759 IConsolePrintF(CC_DEFAULT
, "Completed download of %d", cid
);
1764 * Outputs content state information to console
1765 * @param ci the content info
1767 static void OutputContentState(const ContentInfo
*const ci
)
1769 static const char * const types
[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1770 assert_compile(lengthof(types
) == CONTENT_TYPE_END
- CONTENT_TYPE_BEGIN
);
1771 static const char * const states
[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1772 static const TextColour state_to_colour
[] = { CC_COMMAND
, CC_INFO
, CC_INFO
, CC_WHITE
, CC_ERROR
};
1774 char buf
[sizeof(ci
->md5sum
) * 2 + 1];
1775 md5sumToString(buf
, lastof(buf
), ci
->md5sum
);
1776 IConsolePrintF(state_to_colour
[ci
->state
], "%d, %s, %s, %s, %08X, %s", ci
->id
, types
[ci
->type
- 1], states
[ci
->state
], ci
->name
, ci
->unique_id
, buf
);
1779 DEF_CONSOLE_CMD(ConContent
)
1781 static ContentCallback
*cb
= NULL
;
1783 cb
= new ConsoleContentCallback();
1784 _network_content_client
.AddCallback(cb
);
1788 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1789 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1790 IConsoleHelp(" upgrade: select all items that are upgrades");
1791 IConsoleHelp(" select: select a specific item given by its id or 'all' to select all. If no parameter is given, all selected content will be listed");
1792 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1793 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1794 IConsoleHelp(" download: download all content you've selected");
1798 if (strcasecmp(argv
[1], "update") == 0) {
1799 _network_content_client
.RequestContentList((argc
> 2) ? StringToContentType(argv
[2]) : CONTENT_TYPE_END
);
1803 if (strcasecmp(argv
[1], "upgrade") == 0) {
1804 _network_content_client
.SelectUpgrade();
1808 if (strcasecmp(argv
[1], "select") == 0) {
1810 /* List selected content */
1811 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1812 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1813 if ((*iter
)->state
!= ContentInfo::SELECTED
&& (*iter
)->state
!= ContentInfo::AUTOSELECTED
) continue;
1814 OutputContentState(*iter
);
1816 } else if (strcasecmp(argv
[2], "all") == 0) {
1817 _network_content_client
.SelectAll();
1819 _network_content_client
.Select((ContentID
)atoi(argv
[2]));
1824 if (strcasecmp(argv
[1], "unselect") == 0) {
1826 IConsoleError("You must enter the id.");
1829 if (strcasecmp(argv
[2], "all") == 0) {
1830 _network_content_client
.UnselectAll();
1832 _network_content_client
.Unselect((ContentID
)atoi(argv
[2]));
1837 if (strcasecmp(argv
[1], "state") == 0) {
1838 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1839 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1840 if (argc
> 2 && strcasestr((*iter
)->name
, argv
[2]) == NULL
) continue;
1841 OutputContentState(*iter
);
1846 if (strcasecmp(argv
[1], "download") == 0) {
1849 _network_content_client
.DownloadSelectedContent(files
, bytes
);
1850 IConsolePrintF(CC_DEFAULT
, "Downloading %d file(s) (%d bytes)", files
, bytes
);
1856 #endif /* defined(WITH_ZLIB) */
1857 #endif /* ENABLE_NETWORK */
1859 DEF_CONSOLE_CMD(ConSetting
)
1862 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1863 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1867 if (argc
== 1 || argc
> 3) return false;
1870 IConsoleGetSetting(argv
[1]);
1872 IConsoleSetSetting(argv
[1], argv
[2]);
1878 DEF_CONSOLE_CMD(ConSettingNewgame
)
1881 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1882 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1886 if (argc
== 1 || argc
> 3) return false;
1889 IConsoleGetSetting(argv
[1], true);
1891 IConsoleSetSetting(argv
[1], argv
[2], true);
1897 DEF_CONSOLE_CMD(ConListSettings
)
1900 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1904 if (argc
> 2) return false;
1906 IConsoleListSettings((argc
== 2) ? argv
[1] : NULL
);
1910 DEF_CONSOLE_CMD(ConGamelogPrint
)
1912 GamelogPrintConsole();
1916 DEF_CONSOLE_CMD(ConNewGRFReload
)
1919 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1925 extern void PostCheckNewGRFLoadWarnings();
1926 PostCheckNewGRFLoadWarnings();
1930 DEF_CONSOLE_CMD(ConDumpCommandLog
)
1933 IConsoleHelp("Dump log of recently executed commands.");
1938 DumpCommandLog(buffer
, lastof(buffer
));
1939 PrintLineByLine(buffer
);
1948 static void IConsoleDebugLibRegister()
1950 IConsoleCmdRegister("resettile", ConResetTile
);
1951 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1952 IConsoleAliasRegister("dbg_echo2", "echo %!");
1956 /*******************************
1957 * console command registration
1958 *******************************/
1960 void IConsoleStdLibRegister()
1962 IConsoleCmdRegister("debug_level", ConDebugLevel
);
1963 IConsoleCmdRegister("echo", ConEcho
);
1964 IConsoleCmdRegister("echoc", ConEchoC
);
1965 IConsoleCmdRegister("exec", ConExec
);
1966 IConsoleCmdRegister("exit", ConExit
);
1967 IConsoleCmdRegister("part", ConPart
);
1968 IConsoleCmdRegister("help", ConHelp
);
1969 IConsoleCmdRegister("info_cmd", ConInfoCmd
);
1970 IConsoleCmdRegister("list_cmds", ConListCommands
);
1971 IConsoleCmdRegister("list_aliases", ConListAliases
);
1972 IConsoleCmdRegister("newgame", ConNewGame
);
1973 IConsoleCmdRegister("restart", ConRestart
);
1974 IConsoleCmdRegister("getseed", ConGetSeed
);
1975 IConsoleCmdRegister("getdate", ConGetDate
);
1976 IConsoleCmdRegister("quit", ConExit
);
1977 IConsoleCmdRegister("resetengines", ConResetEngines
, ConHookNoNetwork
);
1978 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool
, ConHookNoNetwork
);
1979 IConsoleCmdRegister("return", ConReturn
);
1980 IConsoleCmdRegister("screenshot", ConScreenShot
);
1981 IConsoleCmdRegister("minimap", ConMinimap
);
1982 IConsoleCmdRegister("script", ConScript
);
1983 IConsoleCmdRegister("scrollto", ConScrollToTile
);
1984 IConsoleCmdRegister("alias", ConAlias
);
1985 IConsoleCmdRegister("load", ConLoad
);
1986 IConsoleCmdRegister("rm", ConRemove
);
1987 IConsoleCmdRegister("save", ConSave
);
1988 IConsoleCmdRegister("saveconfig", ConSaveConfig
);
1989 IConsoleCmdRegister("ls", ConListFiles
);
1990 IConsoleCmdRegister("cd", ConChangeDirectory
);
1991 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory
);
1992 IConsoleCmdRegister("clear", ConClearBuffer
);
1993 IConsoleCmdRegister("setting", ConSetting
);
1994 IConsoleCmdRegister("setting_newgame", ConSettingNewgame
);
1995 IConsoleCmdRegister("list_settings",ConListSettings
);
1996 IConsoleCmdRegister("gamelog", ConGamelogPrint
);
1997 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF
);
1999 IConsoleAliasRegister("dir", "ls");
2000 IConsoleAliasRegister("del", "rm %+");
2001 IConsoleAliasRegister("newmap", "newgame");
2002 IConsoleAliasRegister("patch", "setting %+");
2003 IConsoleAliasRegister("set", "setting %+");
2004 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
2005 IConsoleAliasRegister("list_patches", "list_settings %+");
2006 IConsoleAliasRegister("developer", "setting developer %+");
2008 IConsoleCmdRegister("list_ai_libs", ConListAILibs
);
2009 IConsoleCmdRegister("list_ai", ConListAI
);
2010 IConsoleCmdRegister("reload_ai", ConReloadAI
);
2011 IConsoleCmdRegister("rescan_ai", ConRescanAI
);
2012 IConsoleCmdRegister("start_ai", ConStartAI
);
2013 IConsoleCmdRegister("stop_ai", ConStopAI
);
2015 IConsoleCmdRegister("list_game", ConListGame
);
2016 IConsoleCmdRegister("list_game_libs", ConListGameLibs
);
2017 IConsoleCmdRegister("rescan_game", ConRescanGame
);
2019 IConsoleCmdRegister("companies", ConCompanies
);
2020 IConsoleAliasRegister("players", "companies");
2022 /* networking functions */
2023 #ifdef ENABLE_NETWORK
2024 /* Content downloading is only available with ZLIB */
2025 #if defined(WITH_ZLIB)
2026 IConsoleCmdRegister("content", ConContent
);
2027 #endif /* defined(WITH_ZLIB) */
2029 /*** Networking commands ***/
2030 IConsoleCmdRegister("say", ConSay
, ConHookNeedNetwork
);
2031 IConsoleCmdRegister("say_company", ConSayCompany
, ConHookNeedNetwork
);
2032 IConsoleAliasRegister("say_player", "say_company %+");
2033 IConsoleCmdRegister("say_client", ConSayClient
, ConHookNeedNetwork
);
2035 IConsoleCmdRegister("connect", ConNetworkConnect
, ConHookClientOnly
);
2036 IConsoleCmdRegister("clients", ConNetworkClients
, ConHookNeedNetwork
);
2037 IConsoleCmdRegister("status", ConStatus
, ConHookServerOnly
);
2038 IConsoleCmdRegister("server_info", ConServerInfo
, ConHookServerOnly
);
2039 IConsoleAliasRegister("info", "server_info");
2040 IConsoleCmdRegister("reconnect", ConNetworkReconnect
, ConHookClientOnly
);
2041 IConsoleCmdRegister("rcon", ConRcon
, ConHookNeedNetwork
);
2043 IConsoleCmdRegister("join", ConJoinCompany
, ConHookNeedNetwork
);
2044 IConsoleAliasRegister("spectate", "join 255");
2045 IConsoleCmdRegister("move", ConMoveClient
, ConHookServerOnly
);
2046 IConsoleCmdRegister("reset_company", ConResetCompany
, ConHookServerOnly
);
2047 IConsoleAliasRegister("clean_company", "reset_company %A");
2048 IConsoleCmdRegister("client_name", ConClientNickChange
, ConHookServerOnly
);
2049 IConsoleCmdRegister("kick", ConKick
, ConHookServerOnly
);
2050 IConsoleCmdRegister("ban", ConBan
, ConHookServerOnly
);
2051 IConsoleCmdRegister("unban", ConUnBan
, ConHookServerOnly
);
2052 IConsoleCmdRegister("banlist", ConBanList
, ConHookServerOnly
);
2054 IConsoleCmdRegister("pause", ConPauseGame
, ConHookServerOnly
);
2055 IConsoleCmdRegister("unpause", ConUnpauseGame
, ConHookServerOnly
);
2057 IConsoleCmdRegister("company_pw", ConCompanyPassword
, ConHookNeedNetwork
);
2058 IConsoleAliasRegister("company_password", "company_pw %+");
2060 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2061 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2062 IConsoleAliasRegister("server_pw", "setting server_password %+");
2063 IConsoleAliasRegister("server_password", "setting server_password %+");
2064 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2065 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2066 IConsoleAliasRegister("name", "setting client_name %+");
2067 IConsoleAliasRegister("server_name", "setting server_name %+");
2068 IConsoleAliasRegister("server_port", "setting server_port %+");
2069 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2070 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2071 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2072 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2073 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2074 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2075 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2076 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2077 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2078 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2079 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2080 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2081 #endif /* ENABLE_NETWORK */
2083 /* debugging stuff */
2085 IConsoleDebugLibRegister();
2087 IConsoleCmdRegister("dump_command_log", ConDumpCommandLog
, nullptr);
2088 IConsoleCmdRegister("check_caches", ConCheckCaches
, nullptr);
2090 /* NewGRF development stuff */
2091 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload
, ConHookNewGRFDeveloperTool
);