Also scroll tile separators in the train depot
[openttd/fttd.git] / src / console_cmds.cpp
blob8dbbf7fcecb701157028714787a1719dc49c91e9
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file console_cmds.cpp Implementation of the console hooks. */
12 #include "stdafx.h"
13 #include "console_internal.h"
14 #include "string.h"
15 #include "debug.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"
26 #include "fios.h"
27 #include "fileio_func.h"
28 #include "screenshot.h"
29 #include "genworld.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"
35 #include "gamelog.h"
36 #include "ai/ai.hpp"
37 #include "ai/ai_config.hpp"
38 #include "newgrf.h"
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;
57 /**
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;
69 /**
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 */
85 char *endptr;
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);
102 return NULL;
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)
111 /****************
112 * command hooks
113 ****************/
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.");
125 return false;
127 return true;
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.");
140 return CHR_DISALLOW;
142 return CHR_ALLOW;
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.");
155 return CHR_DISALLOW;
157 return CHR_ALLOW;
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.");
170 return CHR_DISALLOW;
172 return CHR_ALLOW;
176 * Check whether we are in single player mode.
177 * @return True when no network is active.
179 DEF_CONSOLE_HOOK(ConHookNoNetwork)
181 if (_networking) {
182 if (echo) IConsoleError("This command is forbidden in multiplayer.");
183 return CHR_DISALLOW;
185 return CHR_ALLOW;
188 #else
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.");
197 return CHR_DISALLOW;
199 #ifdef ENABLE_NETWORK
200 return ConHookNoNetwork(echo);
201 #else
202 return CHR_ALLOW;
203 #endif
205 return CHR_HIDE;
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)
223 if (argc == 0) {
224 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
225 return true;
228 StartupEngines();
229 return true;
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)
239 if (argc == 0) {
240 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
241 return true;
244 if (_game_mode == GM_MENU) {
245 IConsoleError("This command is only available in game and editor.");
246 return true;
249 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
250 IConsoleError("This can only be done when there are no vehicles in the game.");
251 return true;
254 return true;
257 #ifdef _DEBUG
259 * Reset a tile to bare land in debug mode.
260 * param tile number.
261 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
263 DEF_CONSOLE_CMD(ConResetTile)
265 if (argc == 0) {
266 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
267 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
268 return true;
271 if (argc == 2) {
272 uint32 result;
273 if (GetArgumentInteger(&result, argv[1])) {
274 DoClearSquare((TileIndex)result);
275 return true;
279 return false;
281 #endif /* _DEBUG */
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
289 * and y coordinates.
290 * @return True when either console help was shown or a proper amount of parameters given.
292 DEF_CONSOLE_CMD(ConScrollToTile)
294 switch (argc) {
295 case 0:
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).");
299 return true;
301 case 2: {
302 uint32 result;
303 if (GetArgumentInteger(&result, argv[1])) {
304 if (result >= MapSize()) {
305 IConsolePrint(CC_ERROR, "Tile does not exist");
306 return true;
308 ScrollMainWindowToTile((TileIndex)result);
309 return true;
311 break;
314 case 3: {
315 uint32 x, y;
316 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
317 if (x >= MapSizeX() || y >= MapSizeY()) {
318 IConsolePrint(CC_ERROR, "Tile does not exist");
319 return true;
321 ScrollMainWindowToTile(TileXY(x, y));
322 return true;
324 break;
328 return false;
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)
338 if (argc == 0) {
339 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
340 return true;
343 if (argc == 2) {
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");
349 } else {
350 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
352 free(filename);
353 return true;
356 return false;
360 * Explicitly save the configuration.
361 * @return True.
363 DEF_CONSOLE_CMD(ConSaveConfig)
365 if (argc == 0) {
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.");
368 return true;
371 SaveToConfig();
372 IConsolePrint(CC_DEFAULT, "Saved config.");
373 return true;
376 DEF_CONSOLE_CMD(ConLoad)
378 if (argc == 0) {
379 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
380 return true;
383 if (argc != 2) return false;
385 const char *file = argv[1];
386 const FiosItem *item = FindFile (file);
387 if (item != NULL) {
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);
395 return true;
399 DEF_CONSOLE_CMD(ConRemove)
401 if (argc == 0) {
402 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
403 return true;
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();
415 return true;
419 /* List all the files in the current dir via console */
420 DEF_CONSOLE_CMD(ConListFiles)
422 if (argc == 0) {
423 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
424 return true;
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);
432 return true;
435 /* Change the dir via console */
436 DEF_CONSOLE_CMD(ConChangeDirectory)
438 if (argc == 0) {
439 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
440 return true;
443 if (argc != 2) return false;
445 const char *file = argv[1];
446 const FiosItem *item = FindFile (file, true);
447 if (item != NULL) {
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);
451 break;
452 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
456 InvalidateFileList();
457 return true;
460 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
462 if (argc == 0) {
463 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
464 return true;
467 /* XXX - Workaround for broken file handling */
468 ValidateFileList (true);
469 InvalidateFileList();
471 IConsolePrint (CC_DEFAULT, _console_file_list.path->cur);
472 return true;
475 DEF_CONSOLE_CMD(ConClearBuffer)
477 if (argc == 0) {
478 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
479 return true;
482 IConsoleClearBuffer();
483 SetWindowDirty(WC_CONSOLE, 0);
484 return true;
488 /**********************************
489 * Network Core Console Commands
490 **********************************/
491 #ifdef ENABLE_NETWORK
493 static bool ConKickOrBan(const char *argv, bool ban)
495 uint n;
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");
506 return true;
509 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
510 if (ci == NULL) {
511 IConsoleError("Invalid client");
512 return true;
515 if (!ban) {
516 /* Kick only this client, not all clients with that IP */
517 NetworkServerKickClient(client_id);
518 return true;
521 /* When banning, kick+ban all clients with that IP */
522 n = NetworkServerKickOrBanIP(client_id, ban);
523 } else {
524 n = NetworkServerKickOrBanIP(argv, ban);
527 if (n == 0) {
528 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
529 } else {
530 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
533 return true;
536 DEF_CONSOLE_CMD(ConKick)
538 if (argc == 0) {
539 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
540 IConsoleHelp("For client-id's, see the command 'clients'");
541 return true;
544 if (argc != 2) return false;
546 return ConKickOrBan(argv[1], false);
549 DEF_CONSOLE_CMD(ConBan)
551 if (argc == 0) {
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");
555 return true;
558 if (argc != 2) return false;
560 return ConKickOrBan(argv[1], true);
563 DEF_CONSOLE_CMD(ConUnBan)
565 if (argc == 0) {
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'");
568 return true;
571 if (argc != 2) return false;
573 /* Try by IP. */
574 uint index;
575 for (index = 0; index < _network_ban_list.Length(); index++) {
576 if (strcmp(_network_ban_list[index], argv[1]) == 0) break;
579 /* Try by index. */
580 if (index >= _network_ban_list.Length()) {
581 index = atoi(argv[1]) - 1U; // let it wrap
584 if (index < _network_ban_list.Length()) {
585 char msg[64];
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));
590 } else {
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'");
595 return true;
598 DEF_CONSOLE_CMD(ConBanList)
600 if (argc == 0) {
601 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
602 return true;
605 IConsolePrint(CC_DEFAULT, "Banlist: ");
607 uint i = 1;
608 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
609 IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter);
612 return true;
615 DEF_CONSOLE_CMD(ConPauseGame)
617 if (argc == 0) {
618 IConsoleHelp("Pause a network game. Usage: 'pause'");
619 return true;
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.");
625 } else {
626 IConsolePrint(CC_DEFAULT, "Game is already paused.");
629 return true;
632 DEF_CONSOLE_CMD(ConUnpauseGame)
634 if (argc == 0) {
635 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
636 return true;
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.");
646 } else {
647 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
650 return true;
653 DEF_CONSOLE_CMD(ConRcon)
655 if (argc == 0) {
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");
658 return true;
661 if (argc < 3) return false;
663 if (_network_server) {
664 IConsoleCmdExec(argv[2]);
665 } else {
666 NetworkClientSendRcon(argv[1], argv[2]);
668 return true;
671 DEF_CONSOLE_CMD(ConStatus)
673 if (argc == 0) {
674 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
675 return true;
678 NetworkServerShowStatusToConsole();
679 return true;
682 DEF_CONSOLE_CMD(ConServerInfo)
684 if (argc == 0) {
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'");
687 return true;
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);
694 return true;
697 DEF_CONSOLE_CMD(ConClientNickChange)
699 if (argc != 3) {
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'");
702 return true;
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!");
709 return true;
712 if (NetworkClientInfo::GetByClientID(client_id) == NULL) {
713 IConsoleError("Invalid client");
714 return true;
717 if (!NetworkServerChangeClientName(client_id, argv[2])) {
718 IConsoleError("Cannot give a client a duplicate name");
721 return true;
724 DEF_CONSOLE_CMD(ConJoinCompany)
726 if (argc < 2) {
727 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
728 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
729 return true;
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);
737 return true;
740 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
741 IConsoleError("You are already there!");
742 return true;
745 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
746 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
747 return true;
750 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
751 IConsoleError("Cannot join AI company.");
752 return true;
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);
758 return true;
761 /* non-dedicated server may just do the move! */
762 if (_network_server) {
763 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
764 } else {
765 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
768 return true;
771 DEF_CONSOLE_CMD(ConMoveClient)
773 if (argc < 3) {
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");
776 return true;
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 */
783 if (ci == NULL) {
784 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
785 return true;
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);
790 return true;
793 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
794 IConsoleError("You cannot move clients to AI companies.");
795 return true;
798 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
799 IConsoleError("Silly boy, you cannot move the server!");
800 return true;
803 if (ci->client_playas == company_id) {
804 IConsoleError("You cannot move someone to where he/she already is!");
805 return true;
808 /* we are the server, so force the update */
809 NetworkServerDoMove(ci->client_id, company_id);
811 return true;
814 DEF_CONSOLE_CMD(ConResetCompany)
816 if (argc == 0) {
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.");
819 return true;
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);
829 return true;
832 if (!Company::IsHumanID(index)) {
833 IConsoleError("Company is owned by an AI.");
834 return true;
837 if (NetworkCompanyHasClients(index)) {
838 IConsoleError("Cannot remove company: a client is connected to that company.");
839 return false;
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.");
844 return true;
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.");
851 return true;
854 DEF_CONSOLE_CMD(ConNetworkClients)
856 if (argc == 0) {
857 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
858 return true;
861 NetworkPrintClients();
863 return true;
866 DEF_CONSOLE_CMD(ConNetworkReconnect)
868 if (argc == 0) {
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");
872 return true;
875 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
876 switch (playas) {
877 case 0: playas = COMPANY_NEW_COMPANY; break;
878 case COMPANY_SPECTATOR: /* nothing to do */ break;
879 default:
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) */
882 playas--;
883 if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false;
884 break;
887 if (StrEmpty(_settings_client.network.last_host)) {
888 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
889 return true;
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);
896 return true;
899 DEF_CONSOLE_CMD(ConNetworkConnect)
901 if (argc == 0) {
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");
905 return true;
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;
913 char *ip = argv[1];
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;
929 join_as--;
932 if (port != NULL) {
933 rport = atoi(port);
934 IConsolePrintF(CC_DEFAULT, " port: %s", port);
937 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
939 return true;
942 #endif /* ENABLE_NETWORK */
944 /*********************************
945 * script file console commands
946 *********************************/
948 DEF_CONSOLE_CMD(ConExec)
950 if (argc == 0) {
951 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
952 return true;
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");
961 return true;
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') {
971 *cmdptr = '\0';
972 break;
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);
984 return true;
987 DEF_CONSOLE_CMD(ConReturn)
989 if (argc == 0) {
990 IConsoleHelp("Stop executing a running script. Usage: 'return'");
991 return true;
994 _script_running = false;
995 return true;
998 /*****************************
999 * default console commands
1000 ******************************/
1001 extern bool CloseConsoleLogIfActive();
1003 DEF_CONSOLE_CMD(ConScript)
1005 extern FILE *_iconsole_output_file;
1007 if (argc == 0) {
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");
1010 return true;
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");
1021 return true;
1025 DEF_CONSOLE_CMD(ConEcho)
1027 if (argc == 0) {
1028 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1029 return true;
1032 if (argc < 2) return false;
1033 IConsolePrint(CC_DEFAULT, argv[1]);
1034 return true;
1037 DEF_CONSOLE_CMD(ConEchoC)
1039 if (argc == 0) {
1040 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1041 return true;
1044 if (argc < 3) return false;
1045 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1046 return true;
1049 DEF_CONSOLE_CMD(ConNewGame)
1051 if (argc == 0) {
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.");
1054 return true;
1057 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], NULL, 10) : GENERATE_NEW_SEED);
1058 return true;
1061 DEF_CONSOLE_CMD(ConRestart)
1063 if (argc == 0) {
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");
1069 return true;
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;
1076 return true;
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)
1085 const char *p;
1086 /* Print output line by line */
1087 while ((p = strchr (buf, '\n')) != NULL) {
1088 int len = p - buf;
1089 IConsolePrintF (CC_DEFAULT, "%.*s", len, buf);
1090 buf = p + 1;
1094 DEF_CONSOLE_CMD(ConListAILibs)
1096 sstring<4096> buf;
1097 AI::GetConsoleLibraryList (&buf);
1099 PrintLineByLine (buf.c_str());
1101 return true;
1104 DEF_CONSOLE_CMD(ConListAI)
1106 sstring<4096> buf;
1107 AI::GetConsoleList (&buf);
1109 PrintLineByLine (buf.c_str());
1111 return true;
1114 DEF_CONSOLE_CMD(ConListGameLibs)
1116 sstring<4096> buf;
1117 Game::GetConsoleLibraryList (&buf);
1119 PrintLineByLine (buf.c_str());
1121 return true;
1124 DEF_CONSOLE_CMD(ConListGame)
1126 sstring<4096> buf;
1127 Game::GetConsoleList (&buf);
1129 PrintLineByLine (buf.c_str());
1131 return true;
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.");
1140 return true;
1143 if (_game_mode != GM_NORMAL) {
1144 IConsoleWarning("AIs can only be managed in a game.");
1145 return true;
1148 if (Company::GetNumItems() == Company::Pool::MAX_SIZE) {
1149 IConsoleWarning("Can't start a new AI (no more free slots).");
1150 return true;
1152 if (_networking && !_network_server) {
1153 IConsoleWarning("Only the server can start a new AI.");
1154 return true;
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.");
1159 return true;
1161 if (!AI::CanStartNew()) {
1162 IConsoleWarning("Can't start a new AI.");
1163 return true;
1166 int n = 0;
1167 Company *c;
1168 /* Find the next free slot */
1169 FOR_ALL_COMPANIES(c) {
1170 if (c->index != n) break;
1171 n++;
1174 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1175 if (argc >= 2) {
1176 config->Change(argv[1], -1, true);
1177 if (!config->HasScript()) {
1178 IConsoleWarning("Failed to load the specified AI");
1179 return true;
1181 if (argc == 3) {
1182 config->StringToSettings(argv[2]);
1186 /* Start a new AI company */
1187 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1189 return true;
1192 DEF_CONSOLE_CMD(ConReloadAI)
1194 if (argc != 2) {
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.");
1197 return true;
1200 if (_game_mode != GM_NORMAL) {
1201 IConsoleWarning("AIs can only be managed in a game.");
1202 return true;
1205 if (_networking && !_network_server) {
1206 IConsoleWarning("Only the server can reload an AI.");
1207 return true;
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);
1213 return true;
1216 if (Company::IsHumanID(company_id)) {
1217 IConsoleWarning("Company is not controlled by an AI.");
1218 return true;
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.");
1226 return true;
1229 DEF_CONSOLE_CMD(ConStopAI)
1231 if (argc != 2) {
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.");
1234 return true;
1237 if (_game_mode != GM_NORMAL) {
1238 IConsoleWarning("AIs can only be managed in a game.");
1239 return true;
1242 if (_networking && !_network_server) {
1243 IConsoleWarning("Only the server can stop an AI.");
1244 return true;
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);
1250 return true;
1253 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1254 IConsoleWarning("Company is not controlled by an AI.");
1255 return true;
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.");
1262 return true;
1265 DEF_CONSOLE_CMD(ConRescanAI)
1267 if (argc == 0) {
1268 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1269 return true;
1272 if (_networking && !_network_server) {
1273 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1274 return true;
1277 AI::Rescan();
1279 return true;
1282 DEF_CONSOLE_CMD(ConRescanGame)
1284 if (argc == 0) {
1285 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1286 return true;
1289 if (_networking && !_network_server) {
1290 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1291 return true;
1294 Game::Rescan();
1296 return true;
1299 DEF_CONSOLE_CMD(ConRescanNewGRF)
1301 if (argc == 0) {
1302 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1303 return true;
1306 ScanNewGRFFiles(NULL);
1308 return true;
1311 DEF_CONSOLE_CMD(ConGetSeed)
1313 if (argc == 0) {
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.");
1316 return true;
1319 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1320 return true;
1323 DEF_CONSOLE_CMD(ConGetDate)
1325 if (argc == 0) {
1326 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1327 return true;
1330 YearMonthDay ymd;
1331 ConvertDateToYMD(_date, &ymd);
1332 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", ymd.day, ymd.month + 1, ymd.year);
1333 return true;
1337 DEF_CONSOLE_CMD(ConAlias)
1339 IConsoleAlias *alias;
1341 if (argc == 0) {
1342 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1343 return true;
1346 if (argc < 3) return false;
1348 alias = IConsoleAliasGet(argv[1]);
1349 if (alias == NULL) {
1350 IConsoleAliasRegister(argv[1], argv[2]);
1351 } else {
1352 free(alias->cmdline);
1353 alias->cmdline = xstrdup(argv[2]);
1355 return true;
1358 DEF_CONSOLE_CMD(ConScreenShot)
1360 if (argc == 0) {
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");
1365 return true;
1368 if (argc > 3) return false;
1370 ScreenshotType type = SC_VIEWPORT;
1371 const char *name = NULL;
1373 if (argc > 1) {
1374 if (strcmp(argv[1], "big") == 0) {
1375 /* screenshot big [filename] */
1376 type = SC_ZOOMEDIN;
1377 if (argc > 2) name = argv[2];
1378 } else if (strcmp(argv[1], "giant") == 0) {
1379 /* screenshot giant [filename] */
1380 type = SC_WORLD;
1381 if (argc > 2) name = argv[2];
1382 } else if (strcmp(argv[1], "no_con") == 0) {
1383 /* screenshot no_con [filename] */
1384 IConsoleClose();
1385 if (argc > 2) name = argv[2];
1386 } else if (argc == 2) {
1387 /* screenshot filename */
1388 name = argv[1];
1389 } else {
1390 /* screenshot argv[1] argv[2] - invalid */
1391 return false;
1395 MakeScreenshot(type, name);
1396 return true;
1399 DEF_CONSOLE_CMD(ConInfoCmd)
1401 if (argc == 0) {
1402 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1403 return true;
1406 if (argc < 2) return false;
1408 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1409 if (cmd == NULL) {
1410 IConsoleError("the given command was not found");
1411 return true;
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");
1419 return true;
1422 DEF_CONSOLE_CMD(ConDebugLevel)
1424 if (argc == 0) {
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");
1427 return true;
1430 if (argc > 2) return false;
1432 if (argc == 1) {
1433 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1434 } else {
1435 SetDebugString(argv[1]);
1438 return true;
1441 DEF_CONSOLE_CMD(ConExit)
1443 if (argc == 0) {
1444 IConsoleHelp("Exit the game. Usage: 'exit'");
1445 return true;
1448 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1450 _exit_game = true;
1451 return true;
1454 DEF_CONSOLE_CMD(ConPart)
1456 if (argc == 0) {
1457 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1458 return true;
1461 if (_game_mode != GM_NORMAL) return false;
1463 _switch_mode = SM_MENU;
1464 return true;
1467 DEF_CONSOLE_CMD(ConHelp)
1469 if (argc == 2) {
1470 const IConsoleCmd *cmd;
1471 const IConsoleAlias *alias;
1473 RemoveUnderscores(argv[1]);
1474 cmd = IConsoleCmdGet(argv[1]);
1475 if (cmd != NULL) {
1476 cmd->proc(0, NULL);
1477 return true;
1480 alias = IConsoleAliasGet(argv[1]);
1481 if (alias != NULL) {
1482 cmd = IConsoleCmdGet(alias->cmdline);
1483 if (cmd != NULL) {
1484 cmd->proc(0, NULL);
1485 return true;
1487 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1488 return true;
1491 IConsoleError("command not found");
1492 return true;
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, "");
1504 return true;
1507 DEF_CONSOLE_CMD(ConListCommands)
1509 if (argc == 0) {
1510 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1511 return true;
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);
1520 return true;
1523 DEF_CONSOLE_CMD(ConListAliases)
1525 if (argc == 0) {
1526 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1527 return true;
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);
1536 return true;
1539 DEF_CONSOLE_CMD(ConCompanies)
1541 if (argc == 0) {
1542 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1543 return true;
1546 Company *c;
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 = "";
1554 if (c->is_ai) {
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";
1561 #endif
1563 char colour[512];
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,
1572 password_state);
1575 return true;
1578 #ifdef ENABLE_NETWORK
1580 DEF_CONSOLE_CMD(ConSay)
1582 if (argc == 0) {
1583 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1584 return true;
1587 if (argc != 2) return false;
1589 if (!_network_server) {
1590 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1591 } else {
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);
1596 return true;
1599 DEF_CONSOLE_CMD(ConSayCompany)
1601 if (argc == 0) {
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");
1604 return true;
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);
1612 return true;
1615 if (!_network_server) {
1616 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1617 } else {
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);
1622 return true;
1625 DEF_CONSOLE_CMD(ConSayClient)
1627 if (argc == 0) {
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'");
1630 return true;
1633 if (argc != 3) return false;
1635 if (!_network_server) {
1636 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1637 } else {
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);
1642 return true;
1645 DEF_CONSOLE_CMD(ConCompanyPassword)
1647 if (argc == 0) {
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>\"'";
1654 } else {
1655 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1658 IConsoleHelp(helpmsg);
1659 IConsoleHelp("Use \"*\" to disable the password.");
1660 return true;
1663 CompanyID company_id;
1664 const char *password;
1665 const char *errormsg;
1667 if (argc == 2) {
1668 company_id = _local_company;
1669 password = argv[1];
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);
1673 password = argv[2];
1674 errormsg = "You have to specify the ID of a valid human controlled company.";
1675 } else {
1676 return false;
1679 if (!Company::IsValidHumanID(company_id)) {
1680 IConsoleError(errormsg);
1681 return false;
1684 password = NetworkChangeCompanyPassword(company_id, password);
1686 if (StrEmpty(password)) {
1687 IConsolePrintF(CC_WARNING, "Company password cleared");
1688 } else {
1689 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1692 return true;
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");
1716 void OnDisconnect()
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;
1746 if (cb == NULL) {
1747 cb = new ConsoleContentCallback();
1748 _network_content_client.AddCallback(cb);
1751 if (argc <= 1) {
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");
1759 return true;
1762 if (strcasecmp(argv[1], "update") == 0) {
1763 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1764 return true;
1767 if (strcasecmp(argv[1], "upgrade") == 0) {
1768 _network_content_client.SelectUpgrade();
1769 return true;
1772 if (strcasecmp(argv[1], "select") == 0) {
1773 if (argc <= 2) {
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();
1782 } else {
1783 _network_content_client.Select((ContentID)atoi(argv[2]));
1785 return true;
1788 if (strcasecmp(argv[1], "unselect") == 0) {
1789 if (argc <= 2) {
1790 IConsoleError("You must enter the id.");
1791 return false;
1793 if (strcasecmp(argv[2], "all") == 0) {
1794 _network_content_client.UnselectAll();
1795 } else {
1796 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1798 return true;
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);
1807 return true;
1810 if (strcasecmp(argv[1], "download") == 0) {
1811 uint files;
1812 uint bytes;
1813 _network_content_client.DownloadSelectedContent(files, bytes);
1814 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1815 return true;
1818 return false;
1820 #endif /* defined(WITH_ZLIB) */
1821 #endif /* ENABLE_NETWORK */
1823 DEF_CONSOLE_CMD(ConSetting)
1825 if (argc == 0) {
1826 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1827 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1828 return true;
1831 if (argc == 1 || argc > 3) return false;
1833 if (argc == 2) {
1834 IConsoleGetSetting(argv[1]);
1835 } else {
1836 IConsoleSetSetting(argv[1], argv[2]);
1839 return true;
1842 DEF_CONSOLE_CMD(ConSettingNewgame)
1844 if (argc == 0) {
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.");
1847 return true;
1850 if (argc == 1 || argc > 3) return false;
1852 if (argc == 2) {
1853 IConsoleGetSetting(argv[1], true);
1854 } else {
1855 IConsoleSetSetting(argv[1], argv[2], true);
1858 return true;
1861 DEF_CONSOLE_CMD(ConListSettings)
1863 if (argc == 0) {
1864 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1865 return true;
1868 if (argc > 2) return false;
1870 IConsoleListSettings((argc == 2) ? argv[1] : NULL);
1871 return true;
1874 DEF_CONSOLE_CMD(ConGamelogPrint)
1876 GamelogPrintConsole();
1877 return true;
1880 DEF_CONSOLE_CMD(ConNewGRFReload)
1882 if (argc == 0) {
1883 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1884 return true;
1887 ReloadNewGRFData();
1888 return true;
1891 #ifdef _DEBUG
1892 /******************
1893 * debug commands
1894 ******************/
1896 static void IConsoleDebugLibRegister()
1898 IConsoleCmdRegister("resettile", ConResetTile);
1899 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1900 IConsoleAliasRegister("dbg_echo2", "echo %!");
1902 #endif
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 */
2031 #ifdef _DEBUG
2032 IConsoleDebugLibRegister();
2033 #endif
2035 /* NewGRF development stuff */
2036 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);