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"
16 #include "engine_func.h"
17 #include "landscape.h"
18 #include "saveload/saveload.h"
19 #include "network/network.h"
20 #include "network/network_func.h"
21 #include "network/network_base.h"
22 #include "network/network_admin.h"
23 #include "network/network_client.h"
24 #include "command_func.h"
25 #include "settings_func.h"
27 #include "fileio_func.h"
28 #include "screenshot.h"
30 #include "strings_func.h"
31 #include "viewport_func.h"
32 #include "window_func.h"
33 #include "date_func.h"
34 #include "company_func.h"
37 #include "ai/ai_config.hpp"
39 #include "console_func.h"
40 #include "engine_base.h"
41 #include "game/game.hpp"
42 #include "table/strings.h"
44 /* scriptfile handling */
45 static bool _script_running
; ///< Script is running (used to abort execution when #ConReturn is encountered).
47 static FileList _console_file_list
; ///< File storage cache for the console.
48 static bool _console_file_list_valid
; ///< If set, the file list is valid.
50 /** Declare the file storage cache as being invalid, also clears all stored files. */
51 static void InvalidateFileList (void)
53 _console_file_list
.Clear();
54 _console_file_list_valid
= false;
58 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
59 * @param Always reload the file storage cache.
61 static void ValidateFileList (bool force_reload
)
63 if (force_reload
|| !_console_file_list_valid
) {
64 _console_file_list
.BuildFileList (FT_SAVEGAME
, false);
65 _console_file_list_valid
= true;
70 * Find an item in the console file list by name; warn if it is not found.
71 * @param file The file to find.
72 * @param force_reload Whether to forcibly reload the list.
73 * @return The item found, or NULL if it was not found.
75 static const FiosItem
*FindFile (const char *file
, bool force_reload
= false)
77 ValidateFileList (force_reload
);
79 for (const FiosItem
*item
= _console_file_list
.Begin(); item
!= _console_file_list
.End(); item
++) {
80 if (strcmp (file
, item
->name
) == 0) return item
;
81 if (strcmp (file
, item
->title
) == 0) return item
;
84 /* If no name matches, try to parse it as number */
86 uint i
= strtol (file
, &endptr
, 10);
87 if ((file
!= endptr
) && (*endptr
== '\0')
88 && (i
< _console_file_list
.Length())) {
89 return _console_file_list
.Get (i
);
92 /* As a last effort assume it is an OpenTTD savegame and
93 * that the ".sav" part was not given. */
94 char long_file
[MAX_PATH
];
95 bstrfmt (long_file
, "%s.sav", file
);
96 for (const FiosItem
*item
= _console_file_list
.Begin(); item
!= _console_file_list
.End(); item
++) {
97 if (strcmp (long_file
, item
->name
) == 0) return item
;
98 if (strcmp (long_file
, item
->title
) == 0) return item
;
101 IConsolePrintF (CC_ERROR
, "%s: No such file or directory.", file
);
106 /* console command defines */
107 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
108 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
115 #ifdef ENABLE_NETWORK
118 * Check network availability and inform in console about failure of detection.
119 * @return Network availability.
121 static inline bool NetworkAvailable(bool echo
)
123 if (!_network_available
) {
124 if (echo
) IConsoleError("You cannot use this command because there is no network available.");
131 * Check whether we are a server.
132 * @return Are we a server? True when yes, false otherwise.
134 DEF_CONSOLE_HOOK(ConHookServerOnly
)
136 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
138 if (!_network_server
) {
139 if (echo
) IConsoleError("This command is only available to a network server.");
146 * Check whether we are a client in a network game.
147 * @return Are we a client in a network game? True when yes, false otherwise.
149 DEF_CONSOLE_HOOK(ConHookClientOnly
)
151 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
153 if (_network_server
) {
154 if (echo
) IConsoleError("This command is not available to a network server.");
161 * Check whether we are in a multiplayer game.
162 * @return True when we are client or server in a network game.
164 DEF_CONSOLE_HOOK(ConHookNeedNetwork
)
166 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
168 if (!_networking
|| (!_network_server
&& !MyClient::IsConnected())) {
169 if (echo
) IConsoleError("Not connected. This command is only available in multiplayer.");
176 * Check whether we are in single player mode.
177 * @return True when no network is active.
179 DEF_CONSOLE_HOOK(ConHookNoNetwork
)
182 if (echo
) IConsoleError("This command is forbidden in multiplayer.");
189 # define ConHookNoNetwork NULL
190 #endif /* ENABLE_NETWORK */
192 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool
)
194 if (_settings_client
.gui
.newgrf_developer_tools
) {
195 if (_game_mode
== GM_MENU
) {
196 if (echo
) IConsoleError("This command is only available in game and editor.");
199 #ifdef ENABLE_NETWORK
200 return ConHookNoNetwork(echo
);
209 * Show help for the console.
210 * @param str String to print in the console.
212 static void IConsoleHelp(const char *str
)
214 IConsolePrintF(CC_WARNING
, "- %s", str
);
218 * Reset status of all engines.
219 * @return Will always succeed.
221 DEF_CONSOLE_CMD(ConResetEngines
)
224 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
233 * Reset status of the engine pool.
234 * @return Will always return true.
235 * @note Resetting the pool only succeeds when there are no vehicles ingame.
237 DEF_CONSOLE_CMD(ConResetEnginePool
)
240 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
244 if (_game_mode
== GM_MENU
) {
245 IConsoleError("This command is only available in game and editor.");
249 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
250 IConsoleError("This can only be done when there are no vehicles in the game.");
259 * Reset a tile to bare land in debug mode.
261 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
263 DEF_CONSOLE_CMD(ConResetTile
)
266 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
267 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
273 if (GetArgumentInteger(&result
, argv
[1])) {
274 DoClearSquare((TileIndex
)result
);
284 * Scroll to a tile on the map.
285 * @param arg1 tile tile number or tile x coordinate.
286 * @param arg2 optionally tile y coordinate.
287 * @note When only one argument is given it is intepreted as the tile number.
288 * When two arguments are given, they are interpreted as the tile's x
290 * @return True when either console help was shown or a proper amount of parameters given.
292 DEF_CONSOLE_CMD(ConScrollToTile
)
296 IConsoleHelp("Center the screen on a given tile.");
297 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
298 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
303 if (GetArgumentInteger(&result
, argv
[1])) {
304 if (result
>= MapSize()) {
305 IConsolePrint(CC_ERROR
, "Tile does not exist");
308 ScrollMainWindowToTile((TileIndex
)result
);
316 if (GetArgumentInteger(&x
, argv
[1]) && GetArgumentInteger(&y
, argv
[2])) {
317 if (x
>= MapSizeX() || y
>= MapSizeY()) {
318 IConsolePrint(CC_ERROR
, "Tile does not exist");
321 ScrollMainWindowToTile(TileXY(x
, y
));
332 * Save the map to a file.
333 * @param filename the filename to save the map to.
334 * @return True when help was displayed or the file attempted to be saved.
336 DEF_CONSOLE_CMD(ConSave
)
339 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
344 char *filename
= str_fmt("%s.sav", argv
[1]);
345 IConsolePrint(CC_DEFAULT
, "Saving map...");
347 if (!SaveGame(filename
, SAVE_DIR
)) {
348 IConsolePrint(CC_ERROR
, "Saving map failed");
350 IConsolePrintF(CC_DEFAULT
, "Map successfully saved to %s", filename
);
360 * Explicitly save the configuration.
363 DEF_CONSOLE_CMD(ConSaveConfig
)
366 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
367 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
372 IConsolePrint(CC_DEFAULT
, "Saved config.");
376 DEF_CONSOLE_CMD(ConLoad
)
379 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
383 if (argc
!= 2) return false;
385 const char *file
= argv
[1];
386 const FiosItem
*item
= FindFile (file
);
388 assert (GetAbstractFileType(item
->type
) == FT_SAVEGAME
);
389 _switch_mode
= SM_LOAD_GAME
;
390 _file_to_saveload
.SetMode (item
->type
);
391 _file_to_saveload
.SetName (item
->name
);
392 _file_to_saveload
.SetTitle (item
->title
);
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 const FiosItem
*item
= FindFile (file
);
410 if ((item
!= NULL
) && !FiosDelete (_console_file_list
.path
->cur
, item
->name
)) {
411 IConsolePrintF (CC_ERROR
, "%s: Failed to delete file", file
);
414 InvalidateFileList();
419 /* List all the files in the current dir via console */
420 DEF_CONSOLE_CMD(ConListFiles
)
423 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
427 ValidateFileList (true);
428 for (uint i
= 0; i
< _console_file_list
.Length(); i
++) {
429 IConsolePrintF(CC_DEFAULT
, "%d) %s", i
, _console_file_list
[i
].title
);
435 /* Change the dir via console */
436 DEF_CONSOLE_CMD(ConChangeDirectory
)
439 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
443 if (argc
!= 2) return false;
445 const char *file
= argv
[1];
446 const FiosItem
*item
= FindFile (file
, true);
448 switch (item
->type
) {
449 case FIOS_TYPE_DIR
: case FIOS_TYPE_DRIVE
: case FIOS_TYPE_PARENT
:
450 FiosBrowseTo (_console_file_list
.path
->cur
, item
);
452 default: IConsolePrintF(CC_ERROR
, "%s: Not a directory.", file
);
456 InvalidateFileList();
460 DEF_CONSOLE_CMD(ConPrintWorkingDirectory
)
463 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
467 /* XXX - Workaround for broken file handling */
468 ValidateFileList (true);
469 InvalidateFileList();
471 IConsolePrint (CC_DEFAULT
, _console_file_list
.path
->cur
);
475 DEF_CONSOLE_CMD(ConClearBuffer
)
478 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
482 IConsoleClearBuffer();
483 SetWindowDirty(WC_CONSOLE
, 0);
488 /**********************************
489 * Network Core Console Commands
490 **********************************/
491 #ifdef ENABLE_NETWORK
493 static bool ConKickOrBan(const char *argv
, bool ban
)
497 if (strchr(argv
, '.') == NULL
&& strchr(argv
, ':') == NULL
) { // banning with ID
498 ClientID client_id
= (ClientID
)atoi(argv
);
500 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
501 * kicking frees closes and subsequently free the connection related instances, which we
502 * would be reading from and writing to after returning. So we would read or write data
503 * from freed memory up till the segfault triggers. */
504 if (client_id
== CLIENT_ID_SERVER
|| client_id
== _redirect_console_to_client
) {
505 IConsolePrintF(CC_ERROR
, "ERROR: Silly boy, you can not %s yourself!", ban
? "ban" : "kick");
509 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
511 IConsoleError("Invalid client");
516 /* Kick only this client, not all clients with that IP */
517 NetworkServerKickClient(client_id
);
521 /* When banning, kick+ban all clients with that IP */
522 n
= NetworkServerKickOrBanIP(client_id
, ban
);
524 n
= NetworkServerKickOrBanIP(argv
, ban
);
528 IConsolePrint(CC_DEFAULT
, ban
? "Client not online, address added to banlist" : "Client not found");
530 IConsolePrintF(CC_DEFAULT
, "%sed %u client(s)", ban
? "Bann" : "Kick", n
);
536 DEF_CONSOLE_CMD(ConKick
)
539 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
540 IConsoleHelp("For client-id's, see the command 'clients'");
544 if (argc
!= 2) return false;
546 return ConKickOrBan(argv
[1], false);
549 DEF_CONSOLE_CMD(ConBan
)
552 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
553 IConsoleHelp("For client-id's, see the command 'clients'");
554 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
558 if (argc
!= 2) return false;
560 return ConKickOrBan(argv
[1], true);
563 DEF_CONSOLE_CMD(ConUnBan
)
566 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | banlist-index>'");
567 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
571 if (argc
!= 2) return false;
575 for (index
= 0; index
< _network_ban_list
.Length(); index
++) {
576 if (strcmp(_network_ban_list
[index
], argv
[1]) == 0) break;
580 if (index
>= _network_ban_list
.Length()) {
581 index
= atoi(argv
[1]) - 1U; // let it wrap
584 if (index
< _network_ban_list
.Length()) {
586 bstrfmt (msg
, "Unbanned %s", _network_ban_list
[index
]);
587 IConsolePrint(CC_DEFAULT
, msg
);
588 free(_network_ban_list
[index
]);
589 _network_ban_list
.Erase(_network_ban_list
.Get(index
));
591 IConsolePrint(CC_DEFAULT
, "Invalid list index or IP not in ban-list.");
592 IConsolePrint(CC_DEFAULT
, "For a list of banned IP's, see the command 'banlist'");
598 DEF_CONSOLE_CMD(ConBanList
)
601 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
605 IConsolePrint(CC_DEFAULT
, "Banlist: ");
608 for (char **iter
= _network_ban_list
.Begin(); iter
!= _network_ban_list
.End(); iter
++, i
++) {
609 IConsolePrintF(CC_DEFAULT
, " %d) %s", i
, *iter
);
615 DEF_CONSOLE_CMD(ConPauseGame
)
618 IConsoleHelp("Pause a network game. Usage: 'pause'");
622 if ((_pause_mode
& PM_PAUSED_NORMAL
) == PM_UNPAUSED
) {
623 DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
624 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game paused.");
626 IConsolePrint(CC_DEFAULT
, "Game is already paused.");
632 DEF_CONSOLE_CMD(ConUnpauseGame
)
635 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
639 if ((_pause_mode
& PM_PAUSED_NORMAL
) != PM_UNPAUSED
) {
640 DoCommandP(0, PM_PAUSED_NORMAL
, 0, CMD_PAUSE
);
641 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game unpaused.");
642 } else if ((_pause_mode
& PM_PAUSED_ERROR
) != PM_UNPAUSED
) {
643 IConsolePrint(CC_DEFAULT
, "Game is in error state and cannot be unpaused via console.");
644 } else if (_pause_mode
!= PM_UNPAUSED
) {
645 IConsolePrint(CC_DEFAULT
, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
647 IConsolePrint(CC_DEFAULT
, "Game is already unpaused.");
653 DEF_CONSOLE_CMD(ConRcon
)
656 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
657 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
661 if (argc
< 3) return false;
663 if (_network_server
) {
664 IConsoleCmdExec(argv
[2]);
666 NetworkClientSendRcon(argv
[1], argv
[2]);
671 DEF_CONSOLE_CMD(ConStatus
)
674 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
678 NetworkServerShowStatusToConsole();
682 DEF_CONSOLE_CMD(ConServerInfo
)
685 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
686 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
690 IConsolePrintF(CC_DEFAULT
, "Current/maximum clients: %2d/%2d", _network_game_info
.clients_on
, _settings_client
.network
.max_clients
);
691 IConsolePrintF(CC_DEFAULT
, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client
.network
.max_companies
);
692 IConsolePrintF(CC_DEFAULT
, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client
.network
.max_spectators
);
697 DEF_CONSOLE_CMD(ConClientNickChange
)
700 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
701 IConsoleHelp("For client-id's, see the command 'clients'");
705 ClientID client_id
= (ClientID
)atoi(argv
[1]);
707 if (client_id
== CLIENT_ID_SERVER
) {
708 IConsoleError("Please use the command 'name' to change your own name!");
712 if (NetworkClientInfo::GetByClientID(client_id
) == NULL
) {
713 IConsoleError("Invalid client");
717 if (!NetworkServerChangeClientName(client_id
, argv
[2])) {
718 IConsoleError("Cannot give a client a duplicate name");
724 DEF_CONSOLE_CMD(ConJoinCompany
)
727 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
728 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
732 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) <= MAX_COMPANIES
? atoi(argv
[1]) - 1 : atoi(argv
[1]));
734 /* Check we have a valid company id! */
735 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
736 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
740 if (NetworkClientInfo::GetByClientID(_network_own_client_id
)->client_playas
== company_id
) {
741 IConsoleError("You are already there!");
745 if (company_id
== COMPANY_SPECTATOR
&& NetworkMaxSpectatorsReached()) {
746 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
750 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
751 IConsoleError("Cannot join AI company.");
755 /* Check if the company requires a password */
756 if (NetworkCompanyIsPassworded(company_id
) && argc
< 3) {
757 IConsolePrintF(CC_ERROR
, "Company %d requires a password to join.", company_id
+ 1);
761 /* non-dedicated server may just do the move! */
762 if (_network_server
) {
763 NetworkServerDoMove(CLIENT_ID_SERVER
, company_id
);
765 NetworkClientRequestMove(company_id
, NetworkCompanyIsPassworded(company_id
) ? argv
[2] : "");
771 DEF_CONSOLE_CMD(ConMoveClient
)
774 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
775 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
779 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID((ClientID
)atoi(argv
[1]));
780 CompanyID company_id
= (CompanyID
)(atoi(argv
[2]) <= MAX_COMPANIES
? atoi(argv
[2]) - 1 : atoi(argv
[2]));
782 /* check the client exists */
784 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
788 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
789 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
793 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
794 IConsoleError("You cannot move clients to AI companies.");
798 if (ci
->client_id
== CLIENT_ID_SERVER
&& _network_dedicated
) {
799 IConsoleError("Silly boy, you cannot move the server!");
803 if (ci
->client_playas
== company_id
) {
804 IConsoleError("You cannot move someone to where he/she already is!");
808 /* we are the server, so force the update */
809 NetworkServerDoMove(ci
->client_id
, company_id
);
814 DEF_CONSOLE_CMD(ConResetCompany
)
817 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
818 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
822 if (argc
!= 2) return false;
824 CompanyID index
= (CompanyID
)(atoi(argv
[1]) - 1);
826 /* Check valid range */
827 if (!Company::IsValidID(index
)) {
828 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
832 if (!Company::IsHumanID(index
)) {
833 IConsoleError("Company is owned by an AI.");
837 if (NetworkCompanyHasClients(index
)) {
838 IConsoleError("Cannot remove company: a client is connected to that company.");
841 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
842 if (ci
->client_playas
== index
) {
843 IConsoleError("Cannot remove company: the server is connected to that company.");
847 /* It is safe to remove this company */
848 DoCommandP(0, 2 | index
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
849 IConsolePrint(CC_DEFAULT
, "Company deleted.");
854 DEF_CONSOLE_CMD(ConNetworkClients
)
857 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
861 NetworkPrintClients();
866 DEF_CONSOLE_CMD(ConNetworkReconnect
)
869 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
870 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
871 IConsoleHelp("All others are a certain company with Company 1 being #1");
875 CompanyID playas
= (argc
>= 2) ? (CompanyID
)atoi(argv
[1]) : COMPANY_SPECTATOR
;
877 case 0: playas
= COMPANY_NEW_COMPANY
; break;
878 case COMPANY_SPECTATOR
: /* nothing to do */ break;
880 /* From a user pov 0 is a new company, internally it's different and all
881 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
883 if (playas
< COMPANY_FIRST
|| playas
>= MAX_COMPANIES
) return false;
887 if (StrEmpty(_settings_client
.network
.last_host
)) {
888 IConsolePrint(CC_DEFAULT
, "No server for reconnecting.");
892 /* Don't resolve the address first, just print it directly as it comes from the config file. */
893 IConsolePrintF(CC_DEFAULT
, "Reconnecting to %s:%d...", _settings_client
.network
.last_host
, _settings_client
.network
.last_port
);
895 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), playas
);
899 DEF_CONSOLE_CMD(ConNetworkConnect
)
902 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
903 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
904 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
908 if (argc
< 2) return false;
909 if (_networking
) NetworkDisconnect(); // we are in network-mode, first close it!
911 const char *port
= NULL
;
912 const char *company
= NULL
;
914 /* Default settings: default port and new company */
915 uint16 rport
= NETWORK_DEFAULT_PORT
;
916 CompanyID join_as
= COMPANY_NEW_COMPANY
;
918 ParseConnectionString(&company
, &port
, ip
);
920 IConsolePrintF(CC_DEFAULT
, "Connecting to %s...", ip
);
921 if (company
!= NULL
) {
922 join_as
= (CompanyID
)atoi(company
);
923 IConsolePrintF(CC_DEFAULT
, " company-no: %d", join_as
);
925 /* From a user pov 0 is a new company, internally it's different and all
926 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
927 if (join_as
!= COMPANY_SPECTATOR
) {
928 if (join_as
> MAX_COMPANIES
) return false;
934 IConsolePrintF(CC_DEFAULT
, " port: %s", port
);
937 NetworkClientConnectGame(NetworkAddress(ip
, rport
), join_as
);
942 #endif /* ENABLE_NETWORK */
944 /*********************************
945 * script file console commands
946 *********************************/
948 DEF_CONSOLE_CMD(ConExec
)
951 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
955 if (argc
< 2) return false;
957 FILE *script_file
= FioFOpenFile(argv
[1], "r", BASE_DIR
);
959 if (script_file
== NULL
) {
960 if (argc
== 2 || atoi(argv
[2]) != 0) IConsoleError("script file not found");
964 _script_running
= true;
966 char cmdline
[ICON_CMDLN_SIZE
];
967 while (_script_running
&& fgets(cmdline
, sizeof(cmdline
), script_file
) != NULL
) {
968 /* Remove newline characters from the executing script */
969 for (char *cmdptr
= cmdline
; *cmdptr
!= '\0'; cmdptr
++) {
970 if (*cmdptr
== '\n' || *cmdptr
== '\r') {
975 IConsoleCmdExec(cmdline
);
978 if (ferror(script_file
)) {
979 IConsoleError("Encountered error while trying to read from script file");
982 _script_running
= false;
983 FioFCloseFile(script_file
);
987 DEF_CONSOLE_CMD(ConReturn
)
990 IConsoleHelp("Stop executing a running script. Usage: 'return'");
994 _script_running
= false;
998 /*****************************
999 * default console commands
1000 ******************************/
1001 extern bool CloseConsoleLogIfActive();
1003 DEF_CONSOLE_CMD(ConScript
)
1005 extern FILE *_iconsole_output_file
;
1008 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
1009 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1013 if (!CloseConsoleLogIfActive()) {
1014 if (argc
< 2) return false;
1016 IConsolePrintF(CC_DEFAULT
, "file output started to: %s", argv
[1]);
1017 _iconsole_output_file
= fopen(argv
[1], "ab");
1018 if (_iconsole_output_file
== NULL
) IConsoleError("could not open file");
1025 DEF_CONSOLE_CMD(ConEcho
)
1028 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1032 if (argc
< 2) return false;
1033 IConsolePrint(CC_DEFAULT
, argv
[1]);
1037 DEF_CONSOLE_CMD(ConEchoC
)
1040 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1044 if (argc
< 3) return false;
1045 IConsolePrint((TextColour
)Clamp(atoi(argv
[1]), TC_BEGIN
, TC_END
- 1), argv
[2]);
1049 DEF_CONSOLE_CMD(ConNewGame
)
1052 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1053 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1057 StartNewGameWithoutGUI((argc
== 2) ? strtoul(argv
[1], NULL
, 10) : GENERATE_NEW_SEED
);
1061 DEF_CONSOLE_CMD(ConRestart
)
1064 IConsoleHelp("Restart game. Usage: 'restart'");
1065 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1066 IConsoleHelp("However:");
1067 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1068 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1072 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1073 _settings_game
.game_creation
.map_x
= MapLogX();
1074 _settings_game
.game_creation
.map_y
= FindFirstBit(MapSizeY());
1075 _switch_mode
= SM_RESTARTGAME
;
1080 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1081 * @param buf The buffer to print.
1083 static void PrintLineByLine (const char *buf
)
1086 /* Print output line by line */
1087 while ((p
= strchr (buf
, '\n')) != NULL
) {
1089 IConsolePrintF (CC_DEFAULT
, "%.*s", len
, buf
);
1094 DEF_CONSOLE_CMD(ConListAILibs
)
1097 AI::GetConsoleLibraryList (&buf
);
1099 PrintLineByLine (buf
.c_str());
1104 DEF_CONSOLE_CMD(ConListAI
)
1107 AI::GetConsoleList (&buf
);
1109 PrintLineByLine (buf
.c_str());
1114 DEF_CONSOLE_CMD(ConListGameLibs
)
1117 Game::GetConsoleLibraryList (&buf
);
1119 PrintLineByLine (buf
.c_str());
1124 DEF_CONSOLE_CMD(ConListGame
)
1127 Game::GetConsoleList (&buf
);
1129 PrintLineByLine (buf
.c_str());
1134 DEF_CONSOLE_CMD(ConStartAI
)
1136 if (argc
== 0 || argc
> 3) {
1137 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1138 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1139 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1143 if (_game_mode
!= GM_NORMAL
) {
1144 IConsoleWarning("AIs can only be managed in a game.");
1148 if (Company::GetNumItems() == Company::Pool::MAX_SIZE
) {
1149 IConsoleWarning("Can't start a new AI (no more free slots).");
1152 if (_networking
&& !_network_server
) {
1153 IConsoleWarning("Only the server can start a new AI.");
1156 if (_networking
&& !_settings_game
.ai
.ai_in_multiplayer
) {
1157 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1158 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1161 if (!AI::CanStartNew()) {
1162 IConsoleWarning("Can't start a new AI.");
1168 /* Find the next free slot */
1169 FOR_ALL_COMPANIES(c
) {
1170 if (c
->index
!= n
) break;
1174 AIConfig
*config
= AIConfig::GetConfig((CompanyID
)n
);
1176 config
->Change(argv
[1], -1, true);
1177 if (!config
->HasScript()) {
1178 IConsoleWarning("Failed to load the specified AI");
1182 config
->StringToSettings(argv
[2]);
1186 /* Start a new AI company */
1187 DoCommandP(0, 1 | INVALID_COMPANY
<< 16, 0, CMD_COMPANY_CTRL
);
1192 DEF_CONSOLE_CMD(ConReloadAI
)
1195 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1196 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.");
1200 if (_game_mode
!= GM_NORMAL
) {
1201 IConsoleWarning("AIs can only be managed in a game.");
1205 if (_networking
&& !_network_server
) {
1206 IConsoleWarning("Only the server can reload an AI.");
1210 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1211 if (!Company::IsValidID(company_id
)) {
1212 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1216 if (Company::IsHumanID(company_id
)) {
1217 IConsoleWarning("Company is not controlled by an AI.");
1221 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1222 DoCommandP(0, 2 | company_id
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
1223 DoCommandP(0, 1 | company_id
<< 16, 0, CMD_COMPANY_CTRL
);
1224 IConsolePrint(CC_DEFAULT
, "AI reloaded.");
1229 DEF_CONSOLE_CMD(ConStopAI
)
1232 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1233 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.");
1237 if (_game_mode
!= GM_NORMAL
) {
1238 IConsoleWarning("AIs can only be managed in a game.");
1242 if (_networking
&& !_network_server
) {
1243 IConsoleWarning("Only the server can stop an AI.");
1247 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1248 if (!Company::IsValidID(company_id
)) {
1249 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1253 if (Company::IsHumanID(company_id
) || company_id
== _local_company
) {
1254 IConsoleWarning("Company is not controlled by an AI.");
1258 /* Now kill the company of the AI. */
1259 DoCommandP(0, 2 | company_id
<< 16, CRR_MANUAL
, CMD_COMPANY_CTRL
);
1260 IConsolePrint(CC_DEFAULT
, "AI stopped, company deleted.");
1265 DEF_CONSOLE_CMD(ConRescanAI
)
1268 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1272 if (_networking
&& !_network_server
) {
1273 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1282 DEF_CONSOLE_CMD(ConRescanGame
)
1285 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1289 if (_networking
&& !_network_server
) {
1290 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1299 DEF_CONSOLE_CMD(ConRescanNewGRF
)
1302 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1306 ScanNewGRFFiles(NULL
);
1311 DEF_CONSOLE_CMD(ConGetSeed
)
1314 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1315 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1319 IConsolePrintF(CC_DEFAULT
, "Generation Seed: %u", _settings_game
.game_creation
.generation_seed
);
1323 DEF_CONSOLE_CMD(ConGetDate
)
1326 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1331 ConvertDateToYMD(_date
, &ymd
);
1332 IConsolePrintF(CC_DEFAULT
, "Date: %d-%d-%d", ymd
.day
, ymd
.month
+ 1, ymd
.year
);
1337 DEF_CONSOLE_CMD(ConAlias
)
1339 IConsoleAlias
*alias
;
1342 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1346 if (argc
< 3) return false;
1348 alias
= IConsoleAliasGet(argv
[1]);
1349 if (alias
== NULL
) {
1350 IConsoleAliasRegister(argv
[1], argv
[2]);
1352 free(alias
->cmdline
);
1353 alias
->cmdline
= xstrdup(argv
[2]);
1358 DEF_CONSOLE_CMD(ConScreenShot
)
1361 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1362 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1363 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1364 "screenshots are always drawn without console");
1368 if (argc
> 3) return false;
1370 ScreenshotType type
= SC_VIEWPORT
;
1371 const char *name
= NULL
;
1374 if (strcmp(argv
[1], "big") == 0) {
1375 /* screenshot big [filename] */
1377 if (argc
> 2) name
= argv
[2];
1378 } else if (strcmp(argv
[1], "giant") == 0) {
1379 /* screenshot giant [filename] */
1381 if (argc
> 2) name
= argv
[2];
1382 } else if (strcmp(argv
[1], "no_con") == 0) {
1383 /* screenshot no_con [filename] */
1385 if (argc
> 2) name
= argv
[2];
1386 } else if (argc
== 2) {
1387 /* screenshot filename */
1390 /* screenshot argv[1] argv[2] - invalid */
1395 MakeScreenshot(type
, name
);
1399 DEF_CONSOLE_CMD(ConInfoCmd
)
1402 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1406 if (argc
< 2) return false;
1408 const IConsoleCmd
*cmd
= IConsoleCmdGet(argv
[1]);
1410 IConsoleError("the given command was not found");
1414 IConsolePrintF(CC_DEFAULT
, "command name: %s", cmd
->name
);
1415 IConsolePrintF(CC_DEFAULT
, "command proc: %p", cmd
->proc
);
1417 if (cmd
->hook
!= NULL
) IConsoleWarning("command is hooked");
1422 DEF_CONSOLE_CMD(ConDebugLevel
)
1425 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1426 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1430 if (argc
> 2) return false;
1433 IConsolePrintF(CC_DEFAULT
, "Current debug-level: '%s'", GetDebugString());
1435 SetDebugString(argv
[1]);
1441 DEF_CONSOLE_CMD(ConExit
)
1444 IConsoleHelp("Exit the game. Usage: 'exit'");
1448 if (_game_mode
== GM_NORMAL
&& _settings_client
.gui
.autosave_on_exit
) DoExitSave();
1454 DEF_CONSOLE_CMD(ConPart
)
1457 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1461 if (_game_mode
!= GM_NORMAL
) return false;
1463 _switch_mode
= SM_MENU
;
1467 DEF_CONSOLE_CMD(ConHelp
)
1470 const IConsoleCmd
*cmd
;
1471 const IConsoleAlias
*alias
;
1473 RemoveUnderscores(argv
[1]);
1474 cmd
= IConsoleCmdGet(argv
[1]);
1480 alias
= IConsoleAliasGet(argv
[1]);
1481 if (alias
!= NULL
) {
1482 cmd
= IConsoleCmdGet(alias
->cmdline
);
1487 IConsolePrintF(CC_ERROR
, "ERROR: alias is of special type, please see its execution-line: '%s'", alias
->cmdline
);
1491 IConsoleError("command not found");
1495 IConsolePrint(CC_WARNING
, " ---- OpenTTD Console Help ---- ");
1496 IConsolePrint(CC_DEFAULT
, " - commands: [command to list all commands: list_cmds]");
1497 IConsolePrint(CC_DEFAULT
, " call commands with '<command> <arg2> <arg3>...'");
1498 IConsolePrint(CC_DEFAULT
, " - to assign strings, or use them as arguments, enclose it within quotes");
1499 IConsolePrint(CC_DEFAULT
, " like this: '<command> \"string argument with spaces\"'");
1500 IConsolePrint(CC_DEFAULT
, " - use 'help <command>' to get specific information");
1501 IConsolePrint(CC_DEFAULT
, " - scroll console output with shift + (up | down | pageup | pagedown)");
1502 IConsolePrint(CC_DEFAULT
, " - scroll console input history with the up or down arrows");
1503 IConsolePrint(CC_DEFAULT
, "");
1507 DEF_CONSOLE_CMD(ConListCommands
)
1510 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1514 for (const IConsoleCmd
*cmd
= _iconsole_cmds
; cmd
!= NULL
; cmd
= cmd
->next
) {
1515 if (argv
[1] == NULL
|| strstr(cmd
->name
, argv
[1]) != NULL
) {
1516 if (cmd
->hook
== NULL
|| cmd
->hook(false) != CHR_HIDE
) IConsolePrintF(CC_DEFAULT
, "%s", cmd
->name
);
1523 DEF_CONSOLE_CMD(ConListAliases
)
1526 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1530 for (const IConsoleAlias
*alias
= _iconsole_aliases
; alias
!= NULL
; alias
= alias
->next
) {
1531 if (argv
[1] == NULL
|| strstr(alias
->name
, argv
[1]) != NULL
) {
1532 IConsolePrintF(CC_DEFAULT
, "%s => %s", alias
->name
, alias
->cmdline
);
1539 DEF_CONSOLE_CMD(ConCompanies
)
1542 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1547 FOR_ALL_COMPANIES(c
) {
1548 /* Grab the company name */
1549 char company_name
[512];
1550 SetDParam(0, c
->index
);
1551 GetString (company_name
, STR_COMPANY_NAME
);
1553 const char *password_state
= "";
1555 password_state
= "AI";
1557 #ifdef ENABLE_NETWORK
1558 else if (_network_server
) {
1559 password_state
= StrEmpty(_network_company_states
[c
->index
].password
) ? "unprotected" : "protected";
1564 GetString (colour
, STR_COLOUR_DARK_BLUE
+ _company_colours
[c
->index
]);
1565 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",
1566 c
->index
+ 1, colour
, company_name
,
1567 c
->inaugurated_year
, (int64
)c
->money
, (int64
)c
->current_loan
, (int64
)CalculateCompanyValue(c
),
1568 c
->group_all
[VEH_TRAIN
].num_vehicle
,
1569 c
->group_all
[VEH_ROAD
].num_vehicle
,
1570 c
->group_all
[VEH_AIRCRAFT
].num_vehicle
,
1571 c
->group_all
[VEH_SHIP
].num_vehicle
,
1578 #ifdef ENABLE_NETWORK
1580 DEF_CONSOLE_CMD(ConSay
)
1583 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1587 if (argc
!= 2) return false;
1589 if (!_network_server
) {
1590 NetworkClientSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0 /* param does not matter */, argv
[1]);
1592 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1593 NetworkServerSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0, argv
[1], CLIENT_ID_SERVER
, from_admin
);
1599 DEF_CONSOLE_CMD(ConSayCompany
)
1602 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1603 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1607 if (argc
!= 3) return false;
1609 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1610 if (!Company::IsValidID(company_id
)) {
1611 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1615 if (!_network_server
) {
1616 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2]);
1618 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1619 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2], CLIENT_ID_SERVER
, from_admin
);
1625 DEF_CONSOLE_CMD(ConSayClient
)
1628 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1629 IConsoleHelp("For client-id's, see the command 'clients'");
1633 if (argc
!= 3) return false;
1635 if (!_network_server
) {
1636 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2]);
1638 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1639 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2], CLIENT_ID_SERVER
, from_admin
);
1645 DEF_CONSOLE_CMD(ConCompanyPassword
)
1648 const char *helpmsg
;
1650 if (_network_dedicated
) {
1651 helpmsg
= "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1652 } else if (_network_server
) {
1653 helpmsg
= "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1655 helpmsg
= "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1658 IConsoleHelp(helpmsg
);
1659 IConsoleHelp("Use \"*\" to disable the password.");
1663 CompanyID company_id
;
1664 const char *password
;
1665 const char *errormsg
;
1668 company_id
= _local_company
;
1670 errormsg
= "You have to own a company to make use of this command.";
1671 } else if (argc
== 3 && _network_server
) {
1672 company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1674 errormsg
= "You have to specify the ID of a valid human controlled company.";
1679 if (!Company::IsValidHumanID(company_id
)) {
1680 IConsoleError(errormsg
);
1684 password
= NetworkChangeCompanyPassword(company_id
, password
);
1686 if (StrEmpty(password
)) {
1687 IConsolePrintF(CC_WARNING
, "Company password cleared");
1689 IConsolePrintF(CC_WARNING
, "Company password changed to: %s", password
);
1695 /* Content downloading only is available with ZLIB */
1696 #if defined(WITH_ZLIB)
1697 #include "network/network_content.h"
1699 /** Resolve a string to a content type. */
1700 static ContentType
StringToContentType(const char *str
)
1702 static const char * const inv_lookup
[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1703 for (uint i
= 1 /* there is no type 0 */; i
< lengthof(inv_lookup
); i
++) {
1704 if (strcasecmp(str
, inv_lookup
[i
]) == 0) return (ContentType
)i
;
1706 return CONTENT_TYPE_END
;
1709 /** Asynchronous callback */
1710 struct ConsoleContentCallback
: public ContentCallback
{
1711 void OnConnect(bool success
)
1713 IConsolePrintF(CC_DEFAULT
, "Content server connection %s", success
? "established" : "failed");
1718 IConsolePrintF(CC_DEFAULT
, "Content server connection closed");
1721 void OnDownloadComplete(ContentID cid
)
1723 IConsolePrintF(CC_DEFAULT
, "Completed download of %d", cid
);
1728 * Outputs content state information to console
1729 * @param ci the content info
1731 static void OutputContentState(const ContentInfo
*const ci
)
1733 static const char * const types
[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1734 assert_compile(lengthof(types
) == CONTENT_TYPE_END
- CONTENT_TYPE_BEGIN
);
1735 static const char * const states
[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1736 static const TextColour state_to_colour
[] = { CC_COMMAND
, CC_INFO
, CC_INFO
, CC_WHITE
, CC_ERROR
};
1738 char buf
[sizeof(ci
->md5sum
) * 2 + 1];
1739 md5sumToString (buf
, ci
->md5sum
);
1740 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
);
1743 DEF_CONSOLE_CMD(ConContent
)
1745 static ContentCallback
*cb
= NULL
;
1747 cb
= new ConsoleContentCallback();
1748 _network_content_client
.AddCallback(cb
);
1752 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1753 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1754 IConsoleHelp(" upgrade: select all items that are upgrades");
1755 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");
1756 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1757 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1758 IConsoleHelp(" download: download all content you've selected");
1762 if (strcasecmp(argv
[1], "update") == 0) {
1763 _network_content_client
.RequestContentList((argc
> 2) ? StringToContentType(argv
[2]) : CONTENT_TYPE_END
);
1767 if (strcasecmp(argv
[1], "upgrade") == 0) {
1768 _network_content_client
.SelectUpgrade();
1772 if (strcasecmp(argv
[1], "select") == 0) {
1774 /* List selected content */
1775 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1776 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1777 if ((*iter
)->state
!= ContentInfo::SELECTED
&& (*iter
)->state
!= ContentInfo::AUTOSELECTED
) continue;
1778 OutputContentState(*iter
);
1780 } else if (strcasecmp(argv
[2], "all") == 0) {
1781 _network_content_client
.SelectAll();
1783 _network_content_client
.Select((ContentID
)atoi(argv
[2]));
1788 if (strcasecmp(argv
[1], "unselect") == 0) {
1790 IConsoleError("You must enter the id.");
1793 if (strcasecmp(argv
[2], "all") == 0) {
1794 _network_content_client
.UnselectAll();
1796 _network_content_client
.Unselect((ContentID
)atoi(argv
[2]));
1801 if (strcasecmp(argv
[1], "state") == 0) {
1802 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1803 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1804 if (argc
> 2 && strcasestr((*iter
)->name
, argv
[2]) == NULL
) continue;
1805 OutputContentState(*iter
);
1810 if (strcasecmp(argv
[1], "download") == 0) {
1813 _network_content_client
.DownloadSelectedContent(files
, bytes
);
1814 IConsolePrintF(CC_DEFAULT
, "Downloading %d file(s) (%d bytes)", files
, bytes
);
1820 #endif /* defined(WITH_ZLIB) */
1821 #endif /* ENABLE_NETWORK */
1823 DEF_CONSOLE_CMD(ConSetting
)
1826 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1827 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1831 if (argc
== 1 || argc
> 3) return false;
1834 IConsoleGetSetting(argv
[1]);
1836 IConsoleSetSetting(argv
[1], argv
[2]);
1842 DEF_CONSOLE_CMD(ConSettingNewgame
)
1845 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1846 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1850 if (argc
== 1 || argc
> 3) return false;
1853 IConsoleGetSetting(argv
[1], true);
1855 IConsoleSetSetting(argv
[1], argv
[2], true);
1861 DEF_CONSOLE_CMD(ConListSettings
)
1864 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1868 if (argc
> 2) return false;
1870 IConsoleListSettings((argc
== 2) ? argv
[1] : NULL
);
1874 DEF_CONSOLE_CMD(ConGamelogPrint
)
1876 GamelogPrintConsole();
1880 DEF_CONSOLE_CMD(ConNewGRFReload
)
1883 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1896 static void IConsoleDebugLibRegister()
1898 IConsoleCmdRegister("resettile", ConResetTile
);
1899 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1900 IConsoleAliasRegister("dbg_echo2", "echo %!");
1904 /*******************************
1905 * console command registration
1906 *******************************/
1908 void IConsoleStdLibRegister()
1910 IConsoleCmdRegister("debug_level", ConDebugLevel
);
1911 IConsoleCmdRegister("echo", ConEcho
);
1912 IConsoleCmdRegister("echoc", ConEchoC
);
1913 IConsoleCmdRegister("exec", ConExec
);
1914 IConsoleCmdRegister("exit", ConExit
);
1915 IConsoleCmdRegister("part", ConPart
);
1916 IConsoleCmdRegister("help", ConHelp
);
1917 IConsoleCmdRegister("info_cmd", ConInfoCmd
);
1918 IConsoleCmdRegister("list_cmds", ConListCommands
);
1919 IConsoleCmdRegister("list_aliases", ConListAliases
);
1920 IConsoleCmdRegister("newgame", ConNewGame
);
1921 IConsoleCmdRegister("restart", ConRestart
);
1922 IConsoleCmdRegister("getseed", ConGetSeed
);
1923 IConsoleCmdRegister("getdate", ConGetDate
);
1924 IConsoleCmdRegister("quit", ConExit
);
1925 IConsoleCmdRegister("resetengines", ConResetEngines
, ConHookNoNetwork
);
1926 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool
, ConHookNoNetwork
);
1927 IConsoleCmdRegister("return", ConReturn
);
1928 IConsoleCmdRegister("screenshot", ConScreenShot
);
1929 IConsoleCmdRegister("script", ConScript
);
1930 IConsoleCmdRegister("scrollto", ConScrollToTile
);
1931 IConsoleCmdRegister("alias", ConAlias
);
1932 IConsoleCmdRegister("load", ConLoad
);
1933 IConsoleCmdRegister("rm", ConRemove
);
1934 IConsoleCmdRegister("save", ConSave
);
1935 IConsoleCmdRegister("saveconfig", ConSaveConfig
);
1936 IConsoleCmdRegister("ls", ConListFiles
);
1937 IConsoleCmdRegister("cd", ConChangeDirectory
);
1938 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory
);
1939 IConsoleCmdRegister("clear", ConClearBuffer
);
1940 IConsoleCmdRegister("setting", ConSetting
);
1941 IConsoleCmdRegister("setting_newgame", ConSettingNewgame
);
1942 IConsoleCmdRegister("list_settings",ConListSettings
);
1943 IConsoleCmdRegister("gamelog", ConGamelogPrint
);
1944 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF
);
1946 IConsoleAliasRegister("dir", "ls");
1947 IConsoleAliasRegister("del", "rm %+");
1948 IConsoleAliasRegister("newmap", "newgame");
1949 IConsoleAliasRegister("patch", "setting %+");
1950 IConsoleAliasRegister("set", "setting %+");
1951 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
1952 IConsoleAliasRegister("list_patches", "list_settings %+");
1953 IConsoleAliasRegister("developer", "setting developer %+");
1955 IConsoleCmdRegister("list_ai_libs", ConListAILibs
);
1956 IConsoleCmdRegister("list_ai", ConListAI
);
1957 IConsoleCmdRegister("reload_ai", ConReloadAI
);
1958 IConsoleCmdRegister("rescan_ai", ConRescanAI
);
1959 IConsoleCmdRegister("start_ai", ConStartAI
);
1960 IConsoleCmdRegister("stop_ai", ConStopAI
);
1962 IConsoleCmdRegister("list_game", ConListGame
);
1963 IConsoleCmdRegister("list_game_libs", ConListGameLibs
);
1964 IConsoleCmdRegister("rescan_game", ConRescanGame
);
1966 IConsoleCmdRegister("companies", ConCompanies
);
1967 IConsoleAliasRegister("players", "companies");
1969 /* networking functions */
1970 #ifdef ENABLE_NETWORK
1971 /* Content downloading is only available with ZLIB */
1972 #if defined(WITH_ZLIB)
1973 IConsoleCmdRegister("content", ConContent
);
1974 #endif /* defined(WITH_ZLIB) */
1976 /*** Networking commands ***/
1977 IConsoleCmdRegister("say", ConSay
, ConHookNeedNetwork
);
1978 IConsoleCmdRegister("say_company", ConSayCompany
, ConHookNeedNetwork
);
1979 IConsoleAliasRegister("say_player", "say_company %+");
1980 IConsoleCmdRegister("say_client", ConSayClient
, ConHookNeedNetwork
);
1982 IConsoleCmdRegister("connect", ConNetworkConnect
, ConHookClientOnly
);
1983 IConsoleCmdRegister("clients", ConNetworkClients
, ConHookNeedNetwork
);
1984 IConsoleCmdRegister("status", ConStatus
, ConHookServerOnly
);
1985 IConsoleCmdRegister("server_info", ConServerInfo
, ConHookServerOnly
);
1986 IConsoleAliasRegister("info", "server_info");
1987 IConsoleCmdRegister("reconnect", ConNetworkReconnect
, ConHookClientOnly
);
1988 IConsoleCmdRegister("rcon", ConRcon
, ConHookNeedNetwork
);
1990 IConsoleCmdRegister("join", ConJoinCompany
, ConHookNeedNetwork
);
1991 IConsoleAliasRegister("spectate", "join 255");
1992 IConsoleCmdRegister("move", ConMoveClient
, ConHookServerOnly
);
1993 IConsoleCmdRegister("reset_company", ConResetCompany
, ConHookServerOnly
);
1994 IConsoleAliasRegister("clean_company", "reset_company %A");
1995 IConsoleCmdRegister("client_name", ConClientNickChange
, ConHookServerOnly
);
1996 IConsoleCmdRegister("kick", ConKick
, ConHookServerOnly
);
1997 IConsoleCmdRegister("ban", ConBan
, ConHookServerOnly
);
1998 IConsoleCmdRegister("unban", ConUnBan
, ConHookServerOnly
);
1999 IConsoleCmdRegister("banlist", ConBanList
, ConHookServerOnly
);
2001 IConsoleCmdRegister("pause", ConPauseGame
, ConHookServerOnly
);
2002 IConsoleCmdRegister("unpause", ConUnpauseGame
, ConHookServerOnly
);
2004 IConsoleCmdRegister("company_pw", ConCompanyPassword
, ConHookNeedNetwork
);
2005 IConsoleAliasRegister("company_password", "company_pw %+");
2007 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2008 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2009 IConsoleAliasRegister("server_pw", "setting server_password %+");
2010 IConsoleAliasRegister("server_password", "setting server_password %+");
2011 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2012 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2013 IConsoleAliasRegister("name", "setting client_name %+");
2014 IConsoleAliasRegister("server_name", "setting server_name %+");
2015 IConsoleAliasRegister("server_port", "setting server_port %+");
2016 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2017 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2018 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2019 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2020 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2021 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2022 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2023 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2024 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2025 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2026 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2027 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2028 #endif /* ENABLE_NETWORK */
2030 /* debugging stuff */
2032 IConsoleDebugLibRegister();
2035 /* NewGRF development stuff */
2036 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload
, ConHookNewGRFDeveloperTool
);