Translations update
[openttd/fttd.git] / src / console_cmds.cpp
blob723215da4e89c60b7e985ea82bc22116880ea625
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 /* console command defines */
48 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
49 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
52 /****************
53 * command hooks
54 ****************/
56 #ifdef ENABLE_NETWORK
58 /**
59 * Check network availability and inform in console about failure of detection.
60 * @return Network availability.
62 static inline bool NetworkAvailable(bool echo)
64 if (!_network_available) {
65 if (echo) IConsoleError("You cannot use this command because there is no network available.");
66 return false;
68 return true;
71 /**
72 * Check whether we are a server.
73 * @return Are we a server? True when yes, false otherwise.
75 DEF_CONSOLE_HOOK(ConHookServerOnly)
77 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
79 if (!_network_server) {
80 if (echo) IConsoleError("This command is only available to a network server.");
81 return CHR_DISALLOW;
83 return CHR_ALLOW;
86 /**
87 * Check whether we are a client in a network game.
88 * @return Are we a client in a network game? True when yes, false otherwise.
90 DEF_CONSOLE_HOOK(ConHookClientOnly)
92 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
94 if (_network_server) {
95 if (echo) IConsoleError("This command is not available to a network server.");
96 return CHR_DISALLOW;
98 return CHR_ALLOW;
102 * Check whether we are in a multiplayer game.
103 * @return True when we are client or server in a network game.
105 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
107 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
109 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
110 if (echo) IConsoleError("Not connected. This command is only available in multiplayer.");
111 return CHR_DISALLOW;
113 return CHR_ALLOW;
117 * Check whether we are in single player mode.
118 * @return True when no network is active.
120 DEF_CONSOLE_HOOK(ConHookNoNetwork)
122 if (_networking) {
123 if (echo) IConsoleError("This command is forbidden in multiplayer.");
124 return CHR_DISALLOW;
126 return CHR_ALLOW;
129 #else
130 # define ConHookNoNetwork NULL
131 #endif /* ENABLE_NETWORK */
133 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
135 if (_settings_client.gui.newgrf_developer_tools) {
136 if (_game_mode == GM_MENU) {
137 if (echo) IConsoleError("This command is only available in game and editor.");
138 return CHR_DISALLOW;
140 #ifdef ENABLE_NETWORK
141 return ConHookNoNetwork(echo);
142 #else
143 return CHR_ALLOW;
144 #endif
146 return CHR_HIDE;
150 * Show help for the console.
151 * @param str String to print in the console.
153 static void IConsoleHelp(const char *str)
155 IConsolePrintF(CC_WARNING, "- %s", str);
159 * Reset status of all engines.
160 * @return Will always succeed.
162 DEF_CONSOLE_CMD(ConResetEngines)
164 if (argc == 0) {
165 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
166 return true;
169 StartupEngines();
170 return true;
174 * Reset status of the engine pool.
175 * @return Will always return true.
176 * @note Resetting the pool only succeeds when there are no vehicles ingame.
178 DEF_CONSOLE_CMD(ConResetEnginePool)
180 if (argc == 0) {
181 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
182 return true;
185 if (_game_mode == GM_MENU) {
186 IConsoleError("This command is only available in game and editor.");
187 return true;
190 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
191 IConsoleError("This can only be done when there are no vehicles in the game.");
192 return true;
195 return true;
198 #ifdef _DEBUG
200 * Reset a tile to bare land in debug mode.
201 * param tile number.
202 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
204 DEF_CONSOLE_CMD(ConResetTile)
206 if (argc == 0) {
207 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
208 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
209 return true;
212 if (argc == 2) {
213 uint32 result;
214 if (GetArgumentInteger(&result, argv[1])) {
215 DoClearSquare((TileIndex)result);
216 return true;
220 return false;
222 #endif /* _DEBUG */
225 * Scroll to a tile on the map.
226 * @param arg1 tile tile number or tile x coordinate.
227 * @param arg2 optionally tile y coordinate.
228 * @note When only one argument is given it is intepreted as the tile number.
229 * When two arguments are given, they are interpreted as the tile's x
230 * and y coordinates.
231 * @return True when either console help was shown or a proper amount of parameters given.
233 DEF_CONSOLE_CMD(ConScrollToTile)
235 switch (argc) {
236 case 0:
237 IConsoleHelp("Center the screen on a given tile.");
238 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
239 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
240 return true;
242 case 2: {
243 uint32 result;
244 if (GetArgumentInteger(&result, argv[1])) {
245 if (result >= MapSize()) {
246 IConsolePrint(CC_ERROR, "Tile does not exist");
247 return true;
249 ScrollMainWindowToTile((TileIndex)result);
250 return true;
252 break;
255 case 3: {
256 uint32 x, y;
257 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
258 if (x >= MapSizeX() || y >= MapSizeY()) {
259 IConsolePrint(CC_ERROR, "Tile does not exist");
260 return true;
262 ScrollMainWindowToTile(TileXY(x, y));
263 return true;
265 break;
269 return false;
273 * Save the map to a file.
274 * @param filename the filename to save the map to.
275 * @return True when help was displayed or the file attempted to be saved.
277 DEF_CONSOLE_CMD(ConSave)
279 if (argc == 0) {
280 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
281 return true;
284 if (argc == 2) {
285 char *filename = str_fmt("%s.sav", argv[1]);
286 IConsolePrint(CC_DEFAULT, "Saving map...");
288 if (!SaveGame(filename, SAVE_DIR)) {
289 IConsolePrint(CC_ERROR, "Saving map failed");
290 } else {
291 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
293 free(filename);
294 return true;
297 return false;
301 * Explicitly save the configuration.
302 * @return True.
304 DEF_CONSOLE_CMD(ConSaveConfig)
306 if (argc == 0) {
307 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
308 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
309 return true;
312 SaveToConfig();
313 IConsolePrint(CC_DEFAULT, "Saved config.");
314 return true;
318 * Get savegame file informations.
319 * @param file The savegame filename to return information about. Can be the actual name
320 * or a numbered entry into the filename list.
321 * @return FiosItem The information on the file.
323 static const FiosItem *GetFiosItem(const char *file)
325 _saveload_mode = SLD_LOAD_GAME;
326 BuildFileList();
328 for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
329 if (strcmp(file, item->name) == 0) return item;
330 if (strcmp(file, item->title) == 0) return item;
333 /* If no name matches, try to parse it as number */
334 char *endptr;
335 int i = strtol(file, &endptr, 10);
336 if (file == endptr || *endptr != '\0') i = -1;
338 if (IsInsideMM(i, 0, _fios_items.Length())) return _fios_items.Get(i);
340 /* As a last effort assume it is an OpenTTD savegame and
341 * that the ".sav" part was not given. */
342 char long_file[MAX_PATH];
343 bstrfmt (long_file, "%s.sav", file);
344 for (const FiosItem *item = _fios_items.Begin(); item != _fios_items.End(); item++) {
345 if (strcmp(long_file, item->name) == 0) return item;
346 if (strcmp(long_file, item->title) == 0) return item;
349 return NULL;
353 DEF_CONSOLE_CMD(ConLoad)
355 if (argc == 0) {
356 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
357 return true;
360 if (argc != 2) return false;
362 const char *file = argv[1];
363 const FiosItem *item = GetFiosItem(file);
364 if (item != NULL) {
365 switch (item->type) {
366 case FIOS_TYPE_FILE: case FIOS_TYPE_OLDFILE: {
367 _switch_mode = SM_LOAD_GAME;
368 SetFiosType(item->type);
370 bstrcpy (_file_to_saveload.name, FiosBrowseTo(item));
371 bstrcpy (_file_to_saveload.title, item->title);
372 break;
374 default: IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file);
376 } else {
377 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
380 FiosFreeSavegameList();
381 return true;
385 DEF_CONSOLE_CMD(ConRemove)
387 if (argc == 0) {
388 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
389 return true;
392 if (argc != 2) return false;
394 const char *file = argv[1];
395 const FiosItem *item = GetFiosItem(file);
396 if (item != NULL) {
397 if (!FiosDelete(item->name)) {
398 IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
400 } else {
401 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
404 FiosFreeSavegameList();
405 return true;
409 /* List all the files in the current dir via console */
410 DEF_CONSOLE_CMD(ConListFiles)
412 if (argc == 0) {
413 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
414 return true;
417 BuildFileList();
419 for (uint i = 0; i < _fios_items.Length(); i++) {
420 IConsolePrintF(CC_DEFAULT, "%d) %s", i, _fios_items[i].title);
423 FiosFreeSavegameList();
424 return true;
427 /* Change the dir via console */
428 DEF_CONSOLE_CMD(ConChangeDirectory)
430 if (argc == 0) {
431 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
432 return true;
435 if (argc != 2) return false;
437 const char *file = argv[1];
438 const FiosItem *item = GetFiosItem(file);
439 if (item != NULL) {
440 switch (item->type) {
441 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
442 FiosBrowseTo(item);
443 break;
444 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
446 } else {
447 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
450 FiosFreeSavegameList();
451 return true;
454 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
456 const char *path;
458 if (argc == 0) {
459 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
460 return true;
463 /* XXX - Workaround for broken file handling */
464 FiosGetSavegameList(SLD_LOAD_GAME);
465 FiosFreeSavegameList();
467 FiosGetDescText(&path, NULL);
468 IConsolePrint(CC_DEFAULT, path);
469 return true;
472 DEF_CONSOLE_CMD(ConClearBuffer)
474 if (argc == 0) {
475 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
476 return true;
479 IConsoleClearBuffer();
480 SetWindowDirty(WC_CONSOLE, 0);
481 return true;
485 /**********************************
486 * Network Core Console Commands
487 **********************************/
488 #ifdef ENABLE_NETWORK
490 static bool ConKickOrBan(const char *argv, bool ban)
492 uint n;
494 if (strchr(argv, '.') == NULL && strchr(argv, ':') == NULL) { // banning with ID
495 ClientID client_id = (ClientID)atoi(argv);
497 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
498 * kicking frees closes and subsequently free the connection related instances, which we
499 * would be reading from and writing to after returning. So we would read or write data
500 * from freed memory up till the segfault triggers. */
501 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
502 IConsolePrintF(CC_ERROR, "ERROR: Silly boy, you can not %s yourself!", ban ? "ban" : "kick");
503 return true;
506 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
507 if (ci == NULL) {
508 IConsoleError("Invalid client");
509 return true;
512 if (!ban) {
513 /* Kick only this client, not all clients with that IP */
514 NetworkServerKickClient(client_id);
515 return true;
518 /* When banning, kick+ban all clients with that IP */
519 n = NetworkServerKickOrBanIP(client_id, ban);
520 } else {
521 n = NetworkServerKickOrBanIP(argv, ban);
524 if (n == 0) {
525 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
526 } else {
527 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
530 return true;
533 DEF_CONSOLE_CMD(ConKick)
535 if (argc == 0) {
536 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
537 IConsoleHelp("For client-id's, see the command 'clients'");
538 return true;
541 if (argc != 2) return false;
543 return ConKickOrBan(argv[1], false);
546 DEF_CONSOLE_CMD(ConBan)
548 if (argc == 0) {
549 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
550 IConsoleHelp("For client-id's, see the command 'clients'");
551 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
552 return true;
555 if (argc != 2) return false;
557 return ConKickOrBan(argv[1], true);
560 DEF_CONSOLE_CMD(ConUnBan)
563 if (argc == 0) {
564 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | client-id>'");
565 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
566 return true;
569 if (argc != 2) return false;
571 uint index = (strchr(argv[1], '.') == NULL) ? atoi(argv[1]) : 0;
572 index--;
573 uint i = 0;
575 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
576 if (strcmp(_network_ban_list[i], argv[1]) == 0 || index == i) {
577 free(_network_ban_list[i]);
578 _network_ban_list.Erase(iter);
579 IConsolePrint(CC_DEFAULT, "IP unbanned.");
580 return true;
584 IConsolePrint(CC_DEFAULT, "IP not in ban-list.");
585 return true;
588 DEF_CONSOLE_CMD(ConBanList)
590 if (argc == 0) {
591 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
592 return true;
595 IConsolePrint(CC_DEFAULT, "Banlist: ");
597 uint i = 1;
598 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
599 IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter);
602 return true;
605 DEF_CONSOLE_CMD(ConPauseGame)
607 if (argc == 0) {
608 IConsoleHelp("Pause a network game. Usage: 'pause'");
609 return true;
612 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
613 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
614 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
615 } else {
616 IConsolePrint(CC_DEFAULT, "Game is already paused.");
619 return true;
622 DEF_CONSOLE_CMD(ConUnpauseGame)
624 if (argc == 0) {
625 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
626 return true;
629 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
630 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
631 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
632 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
633 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
634 } else if (_pause_mode != PM_UNPAUSED) {
635 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
636 } else {
637 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
640 return true;
643 DEF_CONSOLE_CMD(ConRcon)
645 if (argc == 0) {
646 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
647 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
648 return true;
651 if (argc < 3) return false;
653 if (_network_server) {
654 IConsoleCmdExec(argv[2]);
655 } else {
656 NetworkClientSendRcon(argv[1], argv[2]);
658 return true;
661 DEF_CONSOLE_CMD(ConStatus)
663 if (argc == 0) {
664 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
665 return true;
668 NetworkServerShowStatusToConsole();
669 return true;
672 DEF_CONSOLE_CMD(ConServerInfo)
674 if (argc == 0) {
675 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
676 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
677 return true;
680 IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients);
681 IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies);
682 IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators);
684 return true;
687 DEF_CONSOLE_CMD(ConClientNickChange)
689 if (argc != 3) {
690 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
691 IConsoleHelp("For client-id's, see the command 'clients'");
692 return true;
695 ClientID client_id = (ClientID)atoi(argv[1]);
697 if (client_id == CLIENT_ID_SERVER) {
698 IConsoleError("Please use the command 'name' to change your own name!");
699 return true;
702 if (NetworkClientInfo::GetByClientID(client_id) == NULL) {
703 IConsoleError("Invalid client");
704 return true;
707 if (!NetworkServerChangeClientName(client_id, argv[2])) {
708 IConsoleError("Cannot give a client a duplicate name");
711 return true;
714 DEF_CONSOLE_CMD(ConJoinCompany)
716 if (argc < 2) {
717 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
718 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
719 return true;
722 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
724 /* Check we have a valid company id! */
725 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
726 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
727 return true;
730 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
731 IConsoleError("You are already there!");
732 return true;
735 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
736 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
737 return true;
740 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
741 IConsoleError("Cannot join AI company.");
742 return true;
745 /* Check if the company requires a password */
746 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
747 IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1);
748 return true;
751 /* non-dedicated server may just do the move! */
752 if (_network_server) {
753 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
754 } else {
755 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
758 return true;
761 DEF_CONSOLE_CMD(ConMoveClient)
763 if (argc < 3) {
764 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
765 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
766 return true;
769 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
770 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
772 /* check the client exists */
773 if (ci == NULL) {
774 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
775 return true;
778 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
779 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
780 return true;
783 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
784 IConsoleError("You cannot move clients to AI companies.");
785 return true;
788 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
789 IConsoleError("Silly boy, you cannot move the server!");
790 return true;
793 if (ci->client_playas == company_id) {
794 IConsoleError("You cannot move someone to where he/she already is!");
795 return true;
798 /* we are the server, so force the update */
799 NetworkServerDoMove(ci->client_id, company_id);
801 return true;
804 DEF_CONSOLE_CMD(ConResetCompany)
806 if (argc == 0) {
807 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
808 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
809 return true;
812 if (argc != 2) return false;
814 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
816 /* Check valid range */
817 if (!Company::IsValidID(index)) {
818 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
819 return true;
822 if (!Company::IsHumanID(index)) {
823 IConsoleError("Company is owned by an AI.");
824 return true;
827 if (NetworkCompanyHasClients(index)) {
828 IConsoleError("Cannot remove company: a client is connected to that company.");
829 return false;
831 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
832 if (ci->client_playas == index) {
833 IConsoleError("Cannot remove company: the server is connected to that company.");
834 return true;
837 /* It is safe to remove this company */
838 DoCommandP(0, 2 | index << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
839 IConsolePrint(CC_DEFAULT, "Company deleted.");
841 return true;
844 DEF_CONSOLE_CMD(ConNetworkClients)
846 if (argc == 0) {
847 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
848 return true;
851 NetworkPrintClients();
853 return true;
856 DEF_CONSOLE_CMD(ConNetworkReconnect)
858 if (argc == 0) {
859 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
860 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
861 IConsoleHelp("All others are a certain company with Company 1 being #1");
862 return true;
865 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
866 switch (playas) {
867 case 0: playas = COMPANY_NEW_COMPANY; break;
868 case COMPANY_SPECTATOR: /* nothing to do */ break;
869 default:
870 /* From a user pov 0 is a new company, internally it's different and all
871 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
872 playas--;
873 if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false;
874 break;
877 if (StrEmpty(_settings_client.network.last_host)) {
878 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
879 return true;
882 /* Don't resolve the address first, just print it directly as it comes from the config file. */
883 IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port);
885 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas);
886 return true;
889 DEF_CONSOLE_CMD(ConNetworkConnect)
891 if (argc == 0) {
892 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
893 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
894 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
895 return true;
898 if (argc < 2) return false;
899 if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
901 const char *port = NULL;
902 const char *company = NULL;
903 char *ip = argv[1];
904 /* Default settings: default port and new company */
905 uint16 rport = NETWORK_DEFAULT_PORT;
906 CompanyID join_as = COMPANY_NEW_COMPANY;
908 ParseConnectionString(&company, &port, ip);
910 IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
911 if (company != NULL) {
912 join_as = (CompanyID)atoi(company);
913 IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
915 /* From a user pov 0 is a new company, internally it's different and all
916 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
917 if (join_as != COMPANY_SPECTATOR) {
918 if (join_as > MAX_COMPANIES) return false;
919 join_as--;
922 if (port != NULL) {
923 rport = atoi(port);
924 IConsolePrintF(CC_DEFAULT, " port: %s", port);
927 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
929 return true;
932 #endif /* ENABLE_NETWORK */
934 /*********************************
935 * script file console commands
936 *********************************/
938 DEF_CONSOLE_CMD(ConExec)
940 if (argc == 0) {
941 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
942 return true;
945 if (argc < 2) return false;
947 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
949 if (script_file == NULL) {
950 if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
951 return true;
954 _script_running = true;
956 char cmdline[ICON_CMDLN_SIZE];
957 while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != NULL) {
958 /* Remove newline characters from the executing script */
959 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
960 if (*cmdptr == '\n' || *cmdptr == '\r') {
961 *cmdptr = '\0';
962 break;
965 IConsoleCmdExec(cmdline);
968 if (ferror(script_file)) {
969 IConsoleError("Encountered error while trying to read from script file");
972 _script_running = false;
973 FioFCloseFile(script_file);
974 return true;
977 DEF_CONSOLE_CMD(ConReturn)
979 if (argc == 0) {
980 IConsoleHelp("Stop executing a running script. Usage: 'return'");
981 return true;
984 _script_running = false;
985 return true;
988 /*****************************
989 * default console commands
990 ******************************/
991 extern bool CloseConsoleLogIfActive();
993 DEF_CONSOLE_CMD(ConScript)
995 extern FILE *_iconsole_output_file;
997 if (argc == 0) {
998 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
999 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1000 return true;
1003 if (!CloseConsoleLogIfActive()) {
1004 if (argc < 2) return false;
1006 IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
1007 _iconsole_output_file = fopen(argv[1], "ab");
1008 if (_iconsole_output_file == NULL) IConsoleError("could not open file");
1011 return true;
1015 DEF_CONSOLE_CMD(ConEcho)
1017 if (argc == 0) {
1018 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1019 return true;
1022 if (argc < 2) return false;
1023 IConsolePrint(CC_DEFAULT, argv[1]);
1024 return true;
1027 DEF_CONSOLE_CMD(ConEchoC)
1029 if (argc == 0) {
1030 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1031 return true;
1034 if (argc < 3) return false;
1035 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1036 return true;
1039 DEF_CONSOLE_CMD(ConNewGame)
1041 if (argc == 0) {
1042 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1043 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1044 return true;
1047 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], NULL, 10) : GENERATE_NEW_SEED);
1048 return true;
1051 DEF_CONSOLE_CMD(ConRestart)
1053 if (argc == 0) {
1054 IConsoleHelp("Restart game. Usage: 'restart'");
1055 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1056 IConsoleHelp("However:");
1057 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1058 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1059 return true;
1062 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1063 _settings_game.game_creation.map_x = MapLogX();
1064 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1065 _switch_mode = SM_RESTARTGAME;
1066 return true;
1070 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1071 * @param buf The buffer to print.
1073 static void PrintLineByLine (const char *buf)
1075 const char *p;
1076 /* Print output line by line */
1077 while ((p = strchr (buf, '\n')) != NULL) {
1078 int len = p - buf;
1079 IConsolePrintF (CC_DEFAULT, "%.*s", len, buf);
1080 buf = p + 1;
1084 DEF_CONSOLE_CMD(ConListAILibs)
1086 sstring<4096> buf;
1087 AI::GetConsoleLibraryList (&buf);
1089 PrintLineByLine (buf.c_str());
1091 return true;
1094 DEF_CONSOLE_CMD(ConListAI)
1096 sstring<4096> buf;
1097 AI::GetConsoleList (&buf);
1099 PrintLineByLine (buf.c_str());
1101 return true;
1104 DEF_CONSOLE_CMD(ConListGameLibs)
1106 sstring<4096> buf;
1107 Game::GetConsoleLibraryList (&buf);
1109 PrintLineByLine (buf.c_str());
1111 return true;
1114 DEF_CONSOLE_CMD(ConListGame)
1116 sstring<4096> buf;
1117 Game::GetConsoleList (&buf);
1119 PrintLineByLine (buf.c_str());
1121 return true;
1124 DEF_CONSOLE_CMD(ConStartAI)
1126 if (argc == 0 || argc > 3) {
1127 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1128 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1129 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1130 return true;
1133 if (_game_mode != GM_NORMAL) {
1134 IConsoleWarning("AIs can only be managed in a game.");
1135 return true;
1138 if (Company::GetNumItems() == Company::Pool::MAX_SIZE) {
1139 IConsoleWarning("Can't start a new AI (no more free slots).");
1140 return true;
1142 if (_networking && !_network_server) {
1143 IConsoleWarning("Only the server can start a new AI.");
1144 return true;
1146 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1147 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1148 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1149 return true;
1151 if (!AI::CanStartNew()) {
1152 IConsoleWarning("Can't start a new AI.");
1153 return true;
1156 int n = 0;
1157 Company *c;
1158 /* Find the next free slot */
1159 FOR_ALL_COMPANIES(c) {
1160 if (c->index != n) break;
1161 n++;
1164 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1165 if (argc >= 2) {
1166 config->Change(argv[1], -1, true);
1167 if (!config->HasScript()) {
1168 IConsoleWarning("Failed to load the specified AI");
1169 return true;
1171 if (argc == 3) {
1172 config->StringToSettings(argv[2]);
1176 /* Start a new AI company */
1177 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1179 return true;
1182 DEF_CONSOLE_CMD(ConReloadAI)
1184 if (argc != 2) {
1185 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1186 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.");
1187 return true;
1190 if (_game_mode != GM_NORMAL) {
1191 IConsoleWarning("AIs can only be managed in a game.");
1192 return true;
1195 if (_networking && !_network_server) {
1196 IConsoleWarning("Only the server can reload an AI.");
1197 return true;
1200 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1201 if (!Company::IsValidID(company_id)) {
1202 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1203 return true;
1206 if (Company::IsHumanID(company_id)) {
1207 IConsoleWarning("Company is not controlled by an AI.");
1208 return true;
1211 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1212 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1213 DoCommandP(0, 1 | company_id << 16, 0, CMD_COMPANY_CTRL);
1214 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1216 return true;
1219 DEF_CONSOLE_CMD(ConStopAI)
1221 if (argc != 2) {
1222 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1223 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.");
1224 return true;
1227 if (_game_mode != GM_NORMAL) {
1228 IConsoleWarning("AIs can only be managed in a game.");
1229 return true;
1232 if (_networking && !_network_server) {
1233 IConsoleWarning("Only the server can stop an AI.");
1234 return true;
1237 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1238 if (!Company::IsValidID(company_id)) {
1239 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1240 return true;
1243 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1244 IConsoleWarning("Company is not controlled by an AI.");
1245 return true;
1248 /* Now kill the company of the AI. */
1249 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1250 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1252 return true;
1255 DEF_CONSOLE_CMD(ConRescanAI)
1257 if (argc == 0) {
1258 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1259 return true;
1262 if (_networking && !_network_server) {
1263 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1264 return true;
1267 AI::Rescan();
1269 return true;
1272 DEF_CONSOLE_CMD(ConRescanGame)
1274 if (argc == 0) {
1275 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1276 return true;
1279 if (_networking && !_network_server) {
1280 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1281 return true;
1284 Game::Rescan();
1286 return true;
1289 DEF_CONSOLE_CMD(ConRescanNewGRF)
1291 if (argc == 0) {
1292 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1293 return true;
1296 ScanNewGRFFiles(NULL);
1298 return true;
1301 DEF_CONSOLE_CMD(ConGetSeed)
1303 if (argc == 0) {
1304 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1305 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1306 return true;
1309 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1310 return true;
1313 DEF_CONSOLE_CMD(ConGetDate)
1315 if (argc == 0) {
1316 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1317 return true;
1320 YearMonthDay ymd;
1321 ConvertDateToYMD(_date, &ymd);
1322 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", ymd.day, ymd.month + 1, ymd.year);
1323 return true;
1327 DEF_CONSOLE_CMD(ConAlias)
1329 IConsoleAlias *alias;
1331 if (argc == 0) {
1332 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1333 return true;
1336 if (argc < 3) return false;
1338 alias = IConsoleAliasGet(argv[1]);
1339 if (alias == NULL) {
1340 IConsoleAliasRegister(argv[1], argv[2]);
1341 } else {
1342 free(alias->cmdline);
1343 alias->cmdline = xstrdup(argv[2]);
1345 return true;
1348 DEF_CONSOLE_CMD(ConScreenShot)
1350 if (argc == 0) {
1351 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1352 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1353 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1354 "screenshots are always drawn without console");
1355 return true;
1358 if (argc > 3) return false;
1360 ScreenshotType type = SC_VIEWPORT;
1361 const char *name = NULL;
1363 if (argc > 1) {
1364 if (strcmp(argv[1], "big") == 0) {
1365 /* screenshot big [filename] */
1366 type = SC_ZOOMEDIN;
1367 if (argc > 2) name = argv[2];
1368 } else if (strcmp(argv[1], "giant") == 0) {
1369 /* screenshot giant [filename] */
1370 type = SC_WORLD;
1371 if (argc > 2) name = argv[2];
1372 } else if (strcmp(argv[1], "no_con") == 0) {
1373 /* screenshot no_con [filename] */
1374 IConsoleClose();
1375 if (argc > 2) name = argv[2];
1376 } else if (argc == 2) {
1377 /* screenshot filename */
1378 name = argv[1];
1379 } else {
1380 /* screenshot argv[1] argv[2] - invalid */
1381 return false;
1385 MakeScreenshot(type, name);
1386 return true;
1389 DEF_CONSOLE_CMD(ConInfoCmd)
1391 if (argc == 0) {
1392 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1393 return true;
1396 if (argc < 2) return false;
1398 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1399 if (cmd == NULL) {
1400 IConsoleError("the given command was not found");
1401 return true;
1404 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1405 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1407 if (cmd->hook != NULL) IConsoleWarning("command is hooked");
1409 return true;
1412 DEF_CONSOLE_CMD(ConDebugLevel)
1414 if (argc == 0) {
1415 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1416 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1417 return true;
1420 if (argc > 2) return false;
1422 if (argc == 1) {
1423 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1424 } else {
1425 SetDebugString(argv[1]);
1428 return true;
1431 DEF_CONSOLE_CMD(ConExit)
1433 if (argc == 0) {
1434 IConsoleHelp("Exit the game. Usage: 'exit'");
1435 return true;
1438 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1440 _exit_game = true;
1441 return true;
1444 DEF_CONSOLE_CMD(ConPart)
1446 if (argc == 0) {
1447 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1448 return true;
1451 if (_game_mode != GM_NORMAL) return false;
1453 _switch_mode = SM_MENU;
1454 return true;
1457 DEF_CONSOLE_CMD(ConHelp)
1459 if (argc == 2) {
1460 const IConsoleCmd *cmd;
1461 const IConsoleAlias *alias;
1463 RemoveUnderscores(argv[1]);
1464 cmd = IConsoleCmdGet(argv[1]);
1465 if (cmd != NULL) {
1466 cmd->proc(0, NULL);
1467 return true;
1470 alias = IConsoleAliasGet(argv[1]);
1471 if (alias != NULL) {
1472 cmd = IConsoleCmdGet(alias->cmdline);
1473 if (cmd != NULL) {
1474 cmd->proc(0, NULL);
1475 return true;
1477 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1478 return true;
1481 IConsoleError("command not found");
1482 return true;
1485 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1486 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1487 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1488 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1489 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1490 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1491 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1492 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1493 IConsolePrint(CC_DEFAULT, "");
1494 return true;
1497 DEF_CONSOLE_CMD(ConListCommands)
1499 if (argc == 0) {
1500 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1501 return true;
1504 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != NULL; cmd = cmd->next) {
1505 if (argv[1] == NULL || strstr(cmd->name, argv[1]) != NULL) {
1506 if (cmd->hook == NULL || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1510 return true;
1513 DEF_CONSOLE_CMD(ConListAliases)
1515 if (argc == 0) {
1516 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1517 return true;
1520 for (const IConsoleAlias *alias = _iconsole_aliases; alias != NULL; alias = alias->next) {
1521 if (argv[1] == NULL || strstr(alias->name, argv[1]) != NULL) {
1522 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1526 return true;
1529 DEF_CONSOLE_CMD(ConCompanies)
1531 if (argc == 0) {
1532 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1533 return true;
1536 Company *c;
1537 FOR_ALL_COMPANIES(c) {
1538 /* Grab the company name */
1539 char company_name[512];
1540 SetDParam(0, c->index);
1541 GetString (company_name, STR_COMPANY_NAME);
1543 const char *password_state = "";
1544 if (c->is_ai) {
1545 password_state = "AI";
1547 #ifdef ENABLE_NETWORK
1548 else if (_network_server) {
1549 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1551 #endif
1553 char colour[512];
1554 GetString (colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index]);
1555 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",
1556 c->index + 1, colour, company_name,
1557 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1558 c->group_all[VEH_TRAIN].num_vehicle,
1559 c->group_all[VEH_ROAD].num_vehicle,
1560 c->group_all[VEH_AIRCRAFT].num_vehicle,
1561 c->group_all[VEH_SHIP].num_vehicle,
1562 password_state);
1565 return true;
1568 #ifdef ENABLE_NETWORK
1570 DEF_CONSOLE_CMD(ConSay)
1572 if (argc == 0) {
1573 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1574 return true;
1577 if (argc != 2) return false;
1579 if (!_network_server) {
1580 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1581 } else {
1582 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1583 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1586 return true;
1589 DEF_CONSOLE_CMD(ConSayCompany)
1591 if (argc == 0) {
1592 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1593 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1594 return true;
1597 if (argc != 3) return false;
1599 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1600 if (!Company::IsValidID(company_id)) {
1601 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1602 return true;
1605 if (!_network_server) {
1606 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1607 } else {
1608 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1609 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1612 return true;
1615 DEF_CONSOLE_CMD(ConSayClient)
1617 if (argc == 0) {
1618 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1619 IConsoleHelp("For client-id's, see the command 'clients'");
1620 return true;
1623 if (argc != 3) return false;
1625 if (!_network_server) {
1626 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1627 } else {
1628 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1629 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1632 return true;
1635 DEF_CONSOLE_CMD(ConCompanyPassword)
1637 if (argc == 0) {
1638 const char *helpmsg;
1640 if (_network_dedicated) {
1641 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1642 } else if (_network_server) {
1643 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1644 } else {
1645 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1648 IConsoleHelp(helpmsg);
1649 IConsoleHelp("Use \"*\" to disable the password.");
1650 return true;
1653 CompanyID company_id;
1654 const char *password;
1655 const char *errormsg;
1657 if (argc == 2) {
1658 company_id = _local_company;
1659 password = argv[1];
1660 errormsg = "You have to own a company to make use of this command.";
1661 } else if (argc == 3 && _network_server) {
1662 company_id = (CompanyID)(atoi(argv[1]) - 1);
1663 password = argv[2];
1664 errormsg = "You have to specify the ID of a valid human controlled company.";
1665 } else {
1666 return false;
1669 if (!Company::IsValidHumanID(company_id)) {
1670 IConsoleError(errormsg);
1671 return false;
1674 password = NetworkChangeCompanyPassword(company_id, password);
1676 if (StrEmpty(password)) {
1677 IConsolePrintF(CC_WARNING, "Company password cleared");
1678 } else {
1679 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1682 return true;
1685 /* Content downloading only is available with ZLIB */
1686 #if defined(WITH_ZLIB)
1687 #include "network/network_content.h"
1689 /** Resolve a string to a content type. */
1690 static ContentType StringToContentType(const char *str)
1692 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1693 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1694 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1696 return CONTENT_TYPE_END;
1699 /** Asynchronous callback */
1700 struct ConsoleContentCallback : public ContentCallback {
1701 void OnConnect(bool success)
1703 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1706 void OnDisconnect()
1708 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1711 void OnDownloadComplete(ContentID cid)
1713 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1718 * Outputs content state information to console
1719 * @param ci the content info
1721 static void OutputContentState(const ContentInfo *const ci)
1723 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1724 assert_compile(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1725 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1726 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1728 char buf[sizeof(ci->md5sum) * 2 + 1];
1729 md5sumToString (buf, ci->md5sum);
1730 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);
1733 DEF_CONSOLE_CMD(ConContent)
1735 static ContentCallback *cb = NULL;
1736 if (cb == NULL) {
1737 cb = new ConsoleContentCallback();
1738 _network_content_client.AddCallback(cb);
1741 if (argc <= 1) {
1742 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1743 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1744 IConsoleHelp(" upgrade: select all items that are upgrades");
1745 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");
1746 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1747 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1748 IConsoleHelp(" download: download all content you've selected");
1749 return true;
1752 if (strcasecmp(argv[1], "update") == 0) {
1753 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1754 return true;
1757 if (strcasecmp(argv[1], "upgrade") == 0) {
1758 _network_content_client.SelectUpgrade();
1759 return true;
1762 if (strcasecmp(argv[1], "select") == 0) {
1763 if (argc <= 2) {
1764 /* List selected content */
1765 IConsolePrintF(CC_WHITE, "id, type, state, name");
1766 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1767 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1768 OutputContentState(*iter);
1770 } else if (strcasecmp(argv[2], "all") == 0) {
1771 _network_content_client.SelectAll();
1772 } else {
1773 _network_content_client.Select((ContentID)atoi(argv[2]));
1775 return true;
1778 if (strcasecmp(argv[1], "unselect") == 0) {
1779 if (argc <= 2) {
1780 IConsoleError("You must enter the id.");
1781 return false;
1783 if (strcasecmp(argv[2], "all") == 0) {
1784 _network_content_client.UnselectAll();
1785 } else {
1786 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1788 return true;
1791 if (strcasecmp(argv[1], "state") == 0) {
1792 IConsolePrintF(CC_WHITE, "id, type, state, name");
1793 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1794 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == NULL) continue;
1795 OutputContentState(*iter);
1797 return true;
1800 if (strcasecmp(argv[1], "download") == 0) {
1801 uint files;
1802 uint bytes;
1803 _network_content_client.DownloadSelectedContent(files, bytes);
1804 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1805 return true;
1808 return false;
1810 #endif /* defined(WITH_ZLIB) */
1811 #endif /* ENABLE_NETWORK */
1813 DEF_CONSOLE_CMD(ConSetting)
1815 if (argc == 0) {
1816 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1817 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1818 return true;
1821 if (argc == 1 || argc > 3) return false;
1823 if (argc == 2) {
1824 IConsoleGetSetting(argv[1]);
1825 } else {
1826 IConsoleSetSetting(argv[1], argv[2]);
1829 return true;
1832 DEF_CONSOLE_CMD(ConSettingNewgame)
1834 if (argc == 0) {
1835 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1836 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1837 return true;
1840 if (argc == 1 || argc > 3) return false;
1842 if (argc == 2) {
1843 IConsoleGetSetting(argv[1], true);
1844 } else {
1845 IConsoleSetSetting(argv[1], argv[2], true);
1848 return true;
1851 DEF_CONSOLE_CMD(ConListSettings)
1853 if (argc == 0) {
1854 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1855 return true;
1858 if (argc > 2) return false;
1860 IConsoleListSettings((argc == 2) ? argv[1] : NULL);
1861 return true;
1864 DEF_CONSOLE_CMD(ConGamelogPrint)
1866 GamelogPrintConsole();
1867 return true;
1870 DEF_CONSOLE_CMD(ConNewGRFReload)
1872 if (argc == 0) {
1873 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1874 return true;
1877 ReloadNewGRFData();
1878 return true;
1881 #ifdef _DEBUG
1882 /******************
1883 * debug commands
1884 ******************/
1886 static void IConsoleDebugLibRegister()
1888 IConsoleCmdRegister("resettile", ConResetTile);
1889 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1890 IConsoleAliasRegister("dbg_echo2", "echo %!");
1892 #endif
1894 /*******************************
1895 * console command registration
1896 *******************************/
1898 void IConsoleStdLibRegister()
1900 IConsoleCmdRegister("debug_level", ConDebugLevel);
1901 IConsoleCmdRegister("echo", ConEcho);
1902 IConsoleCmdRegister("echoc", ConEchoC);
1903 IConsoleCmdRegister("exec", ConExec);
1904 IConsoleCmdRegister("exit", ConExit);
1905 IConsoleCmdRegister("part", ConPart);
1906 IConsoleCmdRegister("help", ConHelp);
1907 IConsoleCmdRegister("info_cmd", ConInfoCmd);
1908 IConsoleCmdRegister("list_cmds", ConListCommands);
1909 IConsoleCmdRegister("list_aliases", ConListAliases);
1910 IConsoleCmdRegister("newgame", ConNewGame);
1911 IConsoleCmdRegister("restart", ConRestart);
1912 IConsoleCmdRegister("getseed", ConGetSeed);
1913 IConsoleCmdRegister("getdate", ConGetDate);
1914 IConsoleCmdRegister("quit", ConExit);
1915 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
1916 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
1917 IConsoleCmdRegister("return", ConReturn);
1918 IConsoleCmdRegister("screenshot", ConScreenShot);
1919 IConsoleCmdRegister("script", ConScript);
1920 IConsoleCmdRegister("scrollto", ConScrollToTile);
1921 IConsoleCmdRegister("alias", ConAlias);
1922 IConsoleCmdRegister("load", ConLoad);
1923 IConsoleCmdRegister("rm", ConRemove);
1924 IConsoleCmdRegister("save", ConSave);
1925 IConsoleCmdRegister("saveconfig", ConSaveConfig);
1926 IConsoleCmdRegister("ls", ConListFiles);
1927 IConsoleCmdRegister("cd", ConChangeDirectory);
1928 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
1929 IConsoleCmdRegister("clear", ConClearBuffer);
1930 IConsoleCmdRegister("setting", ConSetting);
1931 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
1932 IConsoleCmdRegister("list_settings",ConListSettings);
1933 IConsoleCmdRegister("gamelog", ConGamelogPrint);
1934 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
1936 IConsoleAliasRegister("dir", "ls");
1937 IConsoleAliasRegister("del", "rm %+");
1938 IConsoleAliasRegister("newmap", "newgame");
1939 IConsoleAliasRegister("patch", "setting %+");
1940 IConsoleAliasRegister("set", "setting %+");
1941 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
1942 IConsoleAliasRegister("list_patches", "list_settings %+");
1943 IConsoleAliasRegister("developer", "setting developer %+");
1945 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
1946 IConsoleCmdRegister("list_ai", ConListAI);
1947 IConsoleCmdRegister("reload_ai", ConReloadAI);
1948 IConsoleCmdRegister("rescan_ai", ConRescanAI);
1949 IConsoleCmdRegister("start_ai", ConStartAI);
1950 IConsoleCmdRegister("stop_ai", ConStopAI);
1952 IConsoleCmdRegister("list_game", ConListGame);
1953 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
1954 IConsoleCmdRegister("rescan_game", ConRescanGame);
1956 IConsoleCmdRegister("companies", ConCompanies);
1957 IConsoleAliasRegister("players", "companies");
1959 /* networking functions */
1960 #ifdef ENABLE_NETWORK
1961 /* Content downloading is only available with ZLIB */
1962 #if defined(WITH_ZLIB)
1963 IConsoleCmdRegister("content", ConContent);
1964 #endif /* defined(WITH_ZLIB) */
1966 /*** Networking commands ***/
1967 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
1968 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
1969 IConsoleAliasRegister("say_player", "say_company %+");
1970 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
1972 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
1973 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
1974 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
1975 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
1976 IConsoleAliasRegister("info", "server_info");
1977 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
1978 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
1980 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
1981 IConsoleAliasRegister("spectate", "join 255");
1982 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
1983 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
1984 IConsoleAliasRegister("clean_company", "reset_company %A");
1985 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
1986 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
1987 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
1988 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
1989 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
1991 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
1992 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
1994 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
1995 IConsoleAliasRegister("company_password", "company_pw %+");
1997 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
1998 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
1999 IConsoleAliasRegister("server_pw", "setting server_password %+");
2000 IConsoleAliasRegister("server_password", "setting server_password %+");
2001 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2002 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2003 IConsoleAliasRegister("name", "setting client_name %+");
2004 IConsoleAliasRegister("server_name", "setting server_name %+");
2005 IConsoleAliasRegister("server_port", "setting server_port %+");
2006 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2007 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2008 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2009 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2010 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2011 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2012 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2013 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2014 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2015 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2016 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2017 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2018 #endif /* ENABLE_NETWORK */
2020 /* debugging stuff */
2021 #ifdef _DEBUG
2022 IConsoleDebugLibRegister();
2023 #endif
2025 /* NewGRF development stuff */
2026 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);