Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / command.cpp
blob59dce3c470175afa96f7823dcdde20fa8c208c42
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 command.cpp Handling of commands. */
12 #include "stdafx.h"
13 #include "landscape.h"
14 #include "error.h"
15 #include "gui.h"
16 #include "command_func.h"
17 #include "network/network_type.h"
18 #include "network/network.h"
19 #include "genworld.h"
20 #include "strings_func.h"
21 #include "texteff.hpp"
22 #include "town.h"
23 #include "date_func.h"
24 #include "company_func.h"
25 #include "company_base.h"
26 #include "signal_func.h"
27 #include "string_func.h"
28 #include "core/backup_type.hpp"
29 #include "object_base.h"
30 #include <array>
32 #include "table/strings.h"
34 #include "safeguards.h"
36 CommandProc CmdBuildRailroadTrack;
37 CommandProc CmdRemoveRailroadTrack;
38 CommandProc CmdBuildSingleRail;
39 CommandProc CmdRemoveSingleRail;
41 CommandProc CmdLandscapeClear;
43 CommandProc CmdBuildBridge;
45 CommandProc CmdBuildRailStation;
46 CommandProc CmdRemoveFromRailStation;
47 CommandProc CmdConvertRail;
49 CommandProc CmdBuildSingleSignal;
50 CommandProc CmdRemoveSingleSignal;
52 CommandProc CmdTerraformLand;
54 CommandProc CmdBuildObject;
55 CommandProc CmdSellLandArea;
57 CommandProc CmdBuildTunnel;
59 CommandProc CmdBuildTrainDepot;
60 CommandProc CmdBuildRailWaypoint;
61 CommandProc CmdRenameWaypoint;
62 CommandProc CmdRemoveFromRailWaypoint;
64 CommandProc CmdBuildRoadStop;
65 CommandProc CmdRemoveRoadStop;
67 CommandProc CmdBuildLongRoad;
68 CommandProc CmdRemoveLongRoad;
69 CommandProc CmdBuildRoad;
71 CommandProc CmdBuildRoadDepot;
73 CommandProc CmdBuildAirport;
74 CommandProc CmdBuildSeaplaneAirport;
76 CommandProc CmdBuildDock;
78 CommandProc CmdBuildShipDepot;
80 CommandProc CmdBuildBuoy;
82 CommandProc CmdPlantTree;
84 CommandProc CmdMoveRailVehicle;
86 CommandProc CmdBuildVehicle;
87 CommandProc CmdSellVehicle;
88 CommandProc CmdRefitVehicle;
89 CommandProc CmdSendVehicleToDepot;
90 CommandProc CmdSetVehicleVisibility;
92 CommandProc CmdForceTrainProceed;
93 CommandProc CmdReverseTrainDirection;
95 CommandProc CmdClearOrderBackup;
96 CommandProc CmdModifyOrder;
97 CommandProc CmdSkipToOrder;
98 CommandProc CmdDeleteOrder;
99 CommandProc CmdInsertOrder;
100 CommandProc CmdChangeServiceInt;
102 CommandProc CmdBuildIndustry;
104 CommandProc CmdSetCompanyManagerFace;
105 CommandProc CmdSetCompanyColour;
107 CommandProc CmdIncreaseLoan;
108 CommandProc CmdDecreaseLoan;
110 CommandProc CmdWantEnginePreview;
112 CommandProc CmdSetVehicleUnitNumber;
114 CommandProc CmdRenameVehicle;
115 CommandProc CmdRenameEngine;
117 CommandProc CmdRenameCompany;
118 CommandProc CmdRenamePresident;
120 CommandProc CmdRenameStation;
121 CommandProc CmdRenameDepot;
123 CommandProc CmdPlaceSign;
124 CommandProc CmdRenameSign;
126 CommandProc CmdTurnRoadVeh;
128 CommandProc CmdPause;
130 CommandProc CmdBuyShareInCompany;
131 CommandProc CmdSellShareInCompany;
132 CommandProc CmdBuyCompany;
134 CommandProc CmdFoundTown;
135 CommandProc CmdRenameTown;
136 CommandProc CmdDoTownAction;
137 CommandProc CmdTownGrowthRate;
138 CommandProc CmdTownCargoGoal;
139 CommandProc CmdTownSetText;
140 CommandProc CmdExpandTown;
141 CommandProc CmdDeleteTown;
143 CommandProc CmdChangeSetting;
144 CommandProc CmdChangeCompanySetting;
146 CommandProc CmdOrderRefit;
147 CommandProc CmdCloneOrder;
149 CommandProc CmdClearArea;
151 CommandProc CmdGiveMoney;
152 CommandProc CmdMoneyCheat;
153 CommandProc CmdChangeBankBalance;
154 CommandProc CmdBuildCanal;
155 CommandProc CmdBuildLock;
157 CommandProc CmdCreateSubsidy;
158 CommandProc CmdCompanyCtrl;
159 CommandProc CmdCustomNewsItem;
160 CommandProc CmdCreateGoal;
161 CommandProc CmdRemoveGoal;
162 CommandProc CmdSetGoalText;
163 CommandProc CmdSetGoalProgress;
164 CommandProc CmdSetGoalCompleted;
165 CommandProc CmdGoalQuestion;
166 CommandProc CmdGoalQuestionAnswer;
167 CommandProc CmdCreateStoryPage;
168 CommandProc CmdCreateStoryPageElement;
169 CommandProc CmdUpdateStoryPageElement;
170 CommandProc CmdSetStoryPageTitle;
171 CommandProc CmdSetStoryPageDate;
172 CommandProc CmdShowStoryPage;
173 CommandProc CmdRemoveStoryPage;
174 CommandProc CmdRemoveStoryPageElement;
176 CommandProc CmdLevelLand;
178 CommandProc CmdBuildSignalTrack;
179 CommandProc CmdRemoveSignalTrack;
181 CommandProc CmdSetAutoReplace;
183 CommandProc CmdToggleReuseDepotVehicles;
184 CommandProc CmdToggleKeepRemainingVehicles;
185 CommandProc CmdToggleRefitAsTemplate;
187 CommandProc CmdVirtualTrainFromTemplateVehicle;
188 CommandProc CmdVirtualTrainFromTrain;
189 CommandProc CmdDeleteVirtualTrain;
190 CommandProc CmdBuildVirtualRailVehicle;
191 CommandProc CmdReplaceTemplateVehicle;
193 CommandProc CmdTemplateVehicleFromTrain;
194 CommandProc CmdDeleteTemplateVehicle;
196 CommandProc CmdIssueTemplateReplacement;
197 CommandProc CmdDeleteTemplateReplacement;
199 CommandProc CmdCloneVehicle;
200 CommandProc CmdStartStopVehicle;
201 CommandProc CmdMassStartStopVehicle;
202 CommandProc CmdAutoreplaceVehicle;
203 CommandProc CmdTemplateReplaceVehicle;
204 CommandProc CmdDepotSellAllVehicles;
205 CommandProc CmdGroupSellAllVehicles;
206 CommandProc CmdDepotMassAutoReplace;
208 CommandProc CmdCreateGroup;
209 CommandProc CmdCreateGroupSpecificName;
210 CommandProc CmdAlterGroup;
211 CommandProc CmdDeleteGroup;
212 CommandProc CmdAddVehicleGroup;
213 CommandProc CmdAddSharedVehicleGroup;
214 CommandProc CmdRemoveAllVehiclesGroup;
215 CommandProc CmdAutoGroupVehicles;
216 CommandProc CmdSetGroupReplaceProtection;
218 CommandProc CmdMoveOrder;
219 CommandProc CmdChangeTimetable;
220 CommandProc CmdBulkChangeTimetable;
221 CommandProc CmdSetVehicleOnTime;
222 CommandProc CmdAutomateTimetable;
223 CommandProc CmdConfirmAll;
224 CommandProc CmdReinitSeparation;
226 CommandProc CmdOpenCloseAirport;
228 CommandProc CmdAddPlan;
229 CommandProc CmdAddPlanLine;
230 CommandProc CmdRemovePlan;
231 CommandProc CmdRemovePlanLine;
232 CommandProc CmdChangePlanVisibility;
234 CommandProc CmdProgramSignalTraceRestrict;
236 CommandProc CmdProgramLogicSignal;
238 #define DEF_CMD(proc, flags, type) {proc, #proc, (CommandFlags)flags, type}
241 * The master command table
243 * This table contains all possible CommandProc functions with
244 * the flags which belongs to it. The indices are the same
245 * as the value from the CMD_* enums.
247 static const Command _command_proc_table[] = {
248 DEF_CMD(CmdBuildRailroadTrack, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_RAILROAD_TRACK
249 DEF_CMD(CmdRemoveRailroadTrack, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_RAILROAD_TRACK
250 DEF_CMD(CmdBuildSingleRail, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_SINGLE_RAIL
251 DEF_CMD(CmdRemoveSingleRail, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_SINGLE_RAIL
252 DEF_CMD(CmdLandscapeClear, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_LANDSCAPE_CLEAR
253 DEF_CMD(CmdBuildBridge, CMD_DEITY | CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_BRIDGE
254 DEF_CMD(CmdBuildRailStation, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_RAIL_STATION
255 DEF_CMD(CmdBuildTrainDepot, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_TRAIN_DEPOT
256 DEF_CMD(CmdBuildSingleSignal, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_SIGNALS
257 DEF_CMD(CmdRemoveSingleSignal, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_SIGNALS
258 DEF_CMD(CmdTerraformLand, CMD_ALL_TILES | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_TERRAFORM_LAND
259 DEF_CMD(CmdBuildObject, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_OBJECT
260 DEF_CMD(CmdBuildTunnel, CMD_DEITY | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_TUNNEL
261 DEF_CMD(CmdRemoveFromRailStation, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_FROM_RAIL_STATION
262 DEF_CMD(CmdConvertRail, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_CONVERT_RAIL
263 DEF_CMD(CmdBuildRailWaypoint, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_RAIL_WAYPOINT
264 DEF_CMD(CmdRenameWaypoint, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_WAYPOINT
265 DEF_CMD(CmdRemoveFromRailWaypoint, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_FROM_RAIL_WAYPOINT
267 DEF_CMD(CmdBuildRoadStop, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_ROAD_STOP
268 DEF_CMD(CmdRemoveRoadStop, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_ROAD_STOP
269 DEF_CMD(CmdBuildLongRoad,CMD_DEITY | CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_LONG_ROAD
270 DEF_CMD(CmdRemoveLongRoad, CMD_NO_TEST | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_LONG_ROAD; towns may disallow removing road bits (as they are connected) in test, but in exec they're removed and thus removing is allowed.
271 DEF_CMD(CmdBuildRoad, CMD_DEITY | CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_ROAD
272 DEF_CMD(CmdBuildRoadDepot, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_ROAD_DEPOT
274 DEF_CMD(CmdBuildAirport, CMD_NO_WATER | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_AIRPORT
275 DEF_CMD(CmdBuildSeaplaneAirport, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_SEAPLANE_AIRPORT
276 DEF_CMD(CmdBuildDock, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_DOCK
277 DEF_CMD(CmdBuildShipDepot, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_SHIP_DEPOT
278 DEF_CMD(CmdBuildBuoy, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_BUOY
279 DEF_CMD(CmdPlantTree, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_PLANT_TREE
281 DEF_CMD(CmdBuildVehicle, CMD_CLIENT_ID, CMDT_VEHICLE_CONSTRUCTION ), // CMD_BUILD_VEHICLE
282 DEF_CMD(CmdSellVehicle, CMD_CLIENT_ID, CMDT_VEHICLE_CONSTRUCTION ), // CMD_SELL_VEHICLE
283 DEF_CMD(CmdRefitVehicle, 0, CMDT_VEHICLE_CONSTRUCTION ), // CMD_REFIT_VEHICLE
284 DEF_CMD(CmdSendVehicleToDepot, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_SEND_VEHICLE_TO_DEPOT
285 DEF_CMD(CmdSetVehicleVisibility, 0, CMDT_COMPANY_SETTING ), // CMD_SET_VEHICLE_VISIBILITY
287 DEF_CMD(CmdMoveRailVehicle, CMD_ALL_TILES, CMDT_VEHICLE_CONSTRUCTION ), // CMD_MOVE_RAIL_VEHICLE
288 DEF_CMD(CmdForceTrainProceed, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_FORCE_TRAIN_PROCEED
289 DEF_CMD(CmdReverseTrainDirection, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_REVERSE_TRAIN_DIRECTION
291 DEF_CMD(CmdClearOrderBackup, CMD_CLIENT_ID, CMDT_SERVER_SETTING ), // CMD_CLEAR_ORDER_BACKUP
292 DEF_CMD(CmdModifyOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_MODIFY_ORDER
293 DEF_CMD(CmdSkipToOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_SKIP_TO_ORDER
294 DEF_CMD(CmdDeleteOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_DELETE_ORDER
295 DEF_CMD(CmdInsertOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_INSERT_ORDER
297 DEF_CMD(CmdChangeServiceInt, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_CHANGE_SERVICE_INT
299 DEF_CMD(CmdBuildIndustry, CMD_DEITY, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_INDUSTRY
300 DEF_CMD(CmdSetCompanyManagerFace, 0, CMDT_OTHER_MANAGEMENT ), // CMD_SET_COMPANY_MANAGER_FACE
301 DEF_CMD(CmdSetCompanyColour, 0, CMDT_OTHER_MANAGEMENT ), // CMD_SET_COMPANY_COLOUR
303 DEF_CMD(CmdIncreaseLoan, 0, CMDT_MONEY_MANAGEMENT ), // CMD_INCREASE_LOAN
304 DEF_CMD(CmdDecreaseLoan, 0, CMDT_MONEY_MANAGEMENT ), // CMD_DECREASE_LOAN
306 DEF_CMD(CmdWantEnginePreview, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_WANT_ENGINE_PREVIEW
308 DEF_CMD(CmdSetVehicleUnitNumber, 0, CMDT_OTHER_MANAGEMENT ), // CMD_SET_VEHICLE_UNIT_NUMBER
310 DEF_CMD(CmdRenameVehicle, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_VEHICLE
311 DEF_CMD(CmdRenameEngine, CMD_SERVER, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_ENGINE
313 DEF_CMD(CmdRenameCompany, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_COMPANY
314 DEF_CMD(CmdRenamePresident, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_PRESIDENT
316 DEF_CMD(CmdRenameStation, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_STATION
317 DEF_CMD(CmdRenameDepot, 0, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_DEPOT
319 DEF_CMD(CmdPlaceSign, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_PLACE_SIGN
320 DEF_CMD(CmdRenameSign, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_SIGN
322 DEF_CMD(CmdTurnRoadVeh, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_TURN_ROADVEH
324 DEF_CMD(CmdPause, CMD_SERVER, CMDT_SERVER_SETTING ), // CMD_PAUSE
326 DEF_CMD(CmdBuyShareInCompany, 0, CMDT_MONEY_MANAGEMENT ), // CMD_BUY_SHARE_IN_COMPANY
327 DEF_CMD(CmdSellShareInCompany, 0, CMDT_MONEY_MANAGEMENT ), // CMD_SELL_SHARE_IN_COMPANY
328 DEF_CMD(CmdBuyCompany, 0, CMDT_MONEY_MANAGEMENT ), // CMD_BUY_COMANY
330 DEF_CMD(CmdFoundTown, CMD_DEITY | CMD_NO_TEST, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_FOUND_TOWN; founding random town can fail only in exec run
331 DEF_CMD(CmdRenameTown, CMD_DEITY | CMD_SERVER, CMDT_OTHER_MANAGEMENT ), // CMD_RENAME_TOWN
332 DEF_CMD(CmdDoTownAction, 0, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_DO_TOWN_ACTION
333 DEF_CMD(CmdTownCargoGoal, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_TOWN_CARGO_GOAL
334 DEF_CMD(CmdTownGrowthRate, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_TOWN_GROWTH_RATE
335 DEF_CMD(CmdTownSetText, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_TOWN_SET_TEXT
336 DEF_CMD(CmdExpandTown, CMD_DEITY, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_EXPAND_TOWN
337 DEF_CMD(CmdDeleteTown, CMD_OFFLINE, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_DELETE_TOWN
339 DEF_CMD(CmdOrderRefit, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_ORDER_REFIT
340 DEF_CMD(CmdCloneOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_CLONE_ORDER
342 DEF_CMD(CmdClearArea, CMD_NO_TEST, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_CLEAR_AREA; destroying multi-tile houses makes town rating differ between test and execution
344 DEF_CMD(CmdMoneyCheat, CMD_OFFLINE, CMDT_CHEAT ), // CMD_MONEY_CHEAT
345 DEF_CMD(CmdChangeBankBalance, CMD_DEITY, CMDT_MONEY_MANAGEMENT ), // CMD_CHANGE_BANK_BALANCE
346 DEF_CMD(CmdBuildCanal, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_CANAL
347 DEF_CMD(CmdCreateSubsidy, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_CREATE_SUBSIDY
348 DEF_CMD(CmdCompanyCtrl, CMD_SPECTATOR | CMD_CLIENT_ID, CMDT_SERVER_SETTING ), // CMD_COMPANY_CTRL
349 DEF_CMD(CmdCustomNewsItem, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_CUSTOM_NEWS_ITEM
350 DEF_CMD(CmdCreateGoal, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_CREATE_GOAL
351 DEF_CMD(CmdRemoveGoal, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_REMOVE_GOAL
352 DEF_CMD(CmdSetGoalText, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SET_GOAL_TEXT
353 DEF_CMD(CmdSetGoalProgress, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SET_GOAL_PROGRESS
354 DEF_CMD(CmdSetGoalCompleted, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SET_GOAL_COMPLETED
355 DEF_CMD(CmdGoalQuestion, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_GOAL_QUESTION
356 DEF_CMD(CmdGoalQuestionAnswer, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_GOAL_QUESTION_ANSWER
357 DEF_CMD(CmdCreateStoryPage, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_CREATE_STORY_PAGE
358 DEF_CMD(CmdCreateStoryPageElement, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_CREATE_STORY_PAGE_ELEMENT
359 DEF_CMD(CmdUpdateStoryPageElement, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_UPDATE_STORY_PAGE_ELEMENT
360 DEF_CMD(CmdSetStoryPageTitle, CMD_STR_CTRL | CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SET_STORY_PAGE_TITLE
361 DEF_CMD(CmdSetStoryPageDate, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SET_STORY_PAGE_DATE
362 DEF_CMD(CmdShowStoryPage, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_SHOW_STORY_PAGE
363 DEF_CMD(CmdRemoveStoryPage, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_REMOVE_STORY_PAGE
364 DEF_CMD(CmdRemoveStoryPageElement, CMD_DEITY, CMDT_OTHER_MANAGEMENT ), // CMD_REMOVE_STORY_ELEMENT_PAGE
366 DEF_CMD(CmdLevelLand, CMD_ALL_TILES | CMD_NO_TEST | CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_LEVEL_LAND; test run might clear tiles multiple times, in execution that only happens once
368 DEF_CMD(CmdBuildLock, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_LOCK
370 DEF_CMD(CmdBuildSignalTrack, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_BUILD_SIGNAL_TRACK
371 DEF_CMD(CmdRemoveSignalTrack, CMD_AUTO, CMDT_LANDSCAPE_CONSTRUCTION), // CMD_REMOVE_SIGNAL_TRACK
373 DEF_CMD(CmdGiveMoney, 0, CMDT_MONEY_MANAGEMENT ), // CMD_GIVE_MONEY
374 DEF_CMD(CmdChangeSetting, CMD_SERVER, CMDT_SERVER_SETTING ), // CMD_CHANGE_SETTING
375 DEF_CMD(CmdChangeCompanySetting, 0, CMDT_COMPANY_SETTING ), // CMD_CHANGE_COMPANY_SETTING
376 DEF_CMD(CmdSetAutoReplace, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_SET_AUTOREPLACE
378 DEF_CMD(CmdToggleReuseDepotVehicles, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_TOGGLE_REUSE_DEPOT_VEHICLES
379 DEF_CMD(CmdToggleKeepRemainingVehicles, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_TOGGLE_KEEP_REMAINING_VEHICLES
380 DEF_CMD(CmdToggleRefitAsTemplate, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_TOGGLE_REFIT_AS_TEMPLATE
382 DEF_CMD(CmdVirtualTrainFromTemplateVehicle, CMD_NO_TEST | CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT), // CMD_VIRTUAL_TRAIN_FROM_TEMPLATE_VEHICLE
383 DEF_CMD(CmdVirtualTrainFromTrain, CMD_NO_TEST | CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT), // CMD_VIRTUAL_TRAIN_FROM_TRAIN
384 DEF_CMD(CmdDeleteVirtualTrain, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_DELETE_VIRTUAL_TRAIN
385 DEF_CMD(CmdBuildVirtualRailVehicle, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_BUILD_VIRTUAL_RAIL_VEHICLE
386 DEF_CMD(CmdReplaceTemplateVehicle, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_REPLACE_TEMPLATE_VEHICLE
388 DEF_CMD(CmdTemplateVehicleFromTrain, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_CLONE_TEMPLATE_VEHICLE_FROM_TRAIN
389 DEF_CMD(CmdDeleteTemplateVehicle, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_DELETE_TEMPLATE_VEHICLE
391 DEF_CMD(CmdIssueTemplateReplacement, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_ISSUE_TEMPLATE_REPLACEMENT
392 DEF_CMD(CmdDeleteTemplateReplacement, CMD_ALL_TILES, CMDT_VEHICLE_MANAGEMENT ), // CMD_DELETE_TEMPLATE_REPLACEMENT
394 DEF_CMD(CmdCloneVehicle, CMD_NO_TEST, CMDT_VEHICLE_CONSTRUCTION ), // CMD_CLONE_VEHICLE; NewGRF callbacks influence building and refitting making it impossible to correctly estimate the cost
395 DEF_CMD(CmdStartStopVehicle, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_START_STOP_VEHICLE
396 DEF_CMD(CmdMassStartStopVehicle, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_MASS_START_STOP
397 DEF_CMD(CmdAutoreplaceVehicle, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_AUTOREPLACE_VEHICLE
398 DEF_CMD(CmdTemplateReplaceVehicle, 0, CMDT_VEHICLE_MANAGEMENT ), // CMD_TEMPLATE_REPLACE_VEHICLE
399 DEF_CMD(CmdDepotSellAllVehicles, 0, CMDT_VEHICLE_CONSTRUCTION ), // CMD_DEPOT_SELL_ALL_VEHICLES
400 DEF_CMD(CmdGroupSellAllVehicles, 0, CMDT_VEHICLE_CONSTRUCTION ), // CMD_GROUP_SELL_ALL_VEHICLES
401 DEF_CMD(CmdDepotMassAutoReplace, 0, CMDT_VEHICLE_CONSTRUCTION ), // CMD_DEPOT_MASS_AUTOREPLACE
402 DEF_CMD(CmdCreateGroup, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_CREATE_GROUP
403 DEF_CMD(CmdCreateGroupSpecificName, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_CREATE_GROUP_SPECIFIC_NAME
404 DEF_CMD(CmdDeleteGroup, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_DELETE_GROUP
405 DEF_CMD(CmdAlterGroup, 0, CMDT_OTHER_MANAGEMENT ), // CMD_ALTER_GROUP
406 DEF_CMD(CmdAddVehicleGroup, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_ADD_VEHICLE_GROUP
407 DEF_CMD(CmdAddSharedVehicleGroup, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_ADD_SHARE_VEHICLE_GROUP
408 DEF_CMD(CmdRemoveAllVehiclesGroup, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_REMOVE_ALL_VEHICLES_GROUP
409 DEF_CMD(CmdAutoGroupVehicles, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_AUTO_GROUP_VEHICLES
410 DEF_CMD(CmdSetGroupReplaceProtection, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_SET_GROUP_REPLACE_PROTECTION
411 DEF_CMD(CmdMoveOrder, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_MOVE_ORDER
412 DEF_CMD(CmdChangeTimetable, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_CHANGE_TIMETABLE
413 DEF_CMD(CmdBulkChangeTimetable, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_BULK_CHANGE_TIMETABLE
414 DEF_CMD(CmdSetVehicleOnTime, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_SET_VEHICLE_ON_TIME
415 DEF_CMD(CmdAutomateTimetable, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_AUTOMATE_TIMETABLE
416 DEF_CMD(CmdConfirmAll, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_CONFIRM_ALL
417 DEF_CMD(CmdReinitSeparation, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_REINIT_SEPARATION
419 DEF_CMD(CmdOpenCloseAirport, 0, CMDT_ROUTE_MANAGEMENT ), // CMD_OPEN_CLOSE_AIRPORT
421 DEF_CMD(CmdAddPlan, 0, CMDT_OTHER_MANAGEMENT ), // CMD_ADD_PLAN
422 DEF_CMD(CmdAddPlanLine, 0, CMDT_OTHER_MANAGEMENT ), // CMD_ADD_PLAN_LINE
423 DEF_CMD(CmdRemovePlan, 0, CMDT_OTHER_MANAGEMENT ), // CMD_REMOVE_PLAN
424 DEF_CMD(CmdRemovePlanLine, 0, CMDT_OTHER_MANAGEMENT ), // CMD_REMOVE_PLAN_LINE
425 DEF_CMD(CmdChangePlanVisibility, 0, CMDT_OTHER_MANAGEMENT ), // CMD_CHANGE_PLAN_VISIBILITY
427 DEF_CMD(CmdProgramSignalTraceRestrict, 0, CMDT_OTHER_MANAGEMENT ), // CMD_PROGRAM_TRACERESTRICT_SIGNAL
428 DEF_CMD(CmdProgramLogicSignal, 0, CMDT_OTHER_MANAGEMENT ), // CMD_PROGRAM_LOGIC_SIGNAL
433 * List of flags for a command log entry
435 enum CommandLogEntryFlagEnum {
436 CLEF_NONE = 0x00, ///< no flag is set
437 CLEF_CMD_FAILED = 0x01, ///< command failed
438 CLEF_GENERATING_WORLD = 0x02, ///< generating world
439 CLEF_TEXT = 0x04, ///< have command text
440 CLEF_ESTIMATE_ONLY = 0x08, ///< estimate only
441 CLEF_ONLY_SENDING = 0x10, ///< only sending
442 CLEF_MY_CMD = 0x20, ///< locally generated command
444 DECLARE_ENUM_AS_BIT_SET(CommandLogEntryFlagEnum)
445 typedef SimpleTinyEnumT<CommandLogEntryFlagEnum, byte> CommandLogEntryFlag;
447 struct CommandLogEntry {
448 TileIndex tile;
449 uint32 p1;
450 uint32 p2;
451 uint32 cmd;
452 Date date;
453 DateFract date_fract;
454 CompanyByte current_company;
455 CompanyByte local_company;
456 CommandLogEntryFlag log_flags;
458 CommandLogEntry() { }
460 CommandLogEntry(const CommandCost &res, TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandLogEntryFlag log_flags)
461 : tile(tile), p1(p1), p2(p2), cmd(cmd), date(_date), date_fract(_date_fract),
462 current_company(_current_company), local_company(_local_company), log_flags(log_flags)
464 if (res.Failed()) this->log_flags |= CLEF_CMD_FAILED;
465 if (_generating_world) this->log_flags |= CLEF_GENERATING_WORLD;
469 static std::array<CommandLogEntry, 128> command_log;
470 static unsigned int command_log_count = 0;
471 static unsigned int command_log_next = 0;
473 void ClearCommandLog()
475 command_log_count = 0;
476 command_log_next = 0;
479 char *DumpCommandLog(char *buffer, const char *last)
481 const unsigned int count = min<unsigned int>(command_log_count, command_log.size());
482 unsigned int log_index = command_log_next;
484 buffer += seprintf(buffer, last, "Command Log:\n Showing most recent %u of %u commands\n", count, command_log_count);
486 for (unsigned int i = 0 ; i < count; i++) {
487 if (log_index > 0) {
488 log_index--;
489 } else {
490 log_index = command_log.size() - 1;
492 const CommandLogEntry &entry = command_log[log_index];
494 auto fc = [&](CommandLogEntryFlagEnum flag, char c) -> char {
495 return entry.log_flags & flag ? c : '-';
498 YearMonthDay ymd;
499 ConvertDateToYMD(entry.date, &ymd);
500 buffer += seprintf(buffer, last, " %3u | %4i-%02i-%02i, %2i | ", i, ymd.year, ymd.month + 1, ymd.day, entry.date_fract);
501 buffer += seprintf(buffer, last, "%c%c%c%c%c%c | ",
502 fc(CLEF_MY_CMD, 'm'), fc(CLEF_ONLY_SENDING, 's'), fc(CLEF_ESTIMATE_ONLY, 'e'),
503 fc(CLEF_TEXT, 't'), fc(CLEF_GENERATING_WORLD, 'g'), fc(CLEF_CMD_FAILED, 'f'));
504 buffer += seprintf(buffer, last, " %7d x %7d, p1: 0x%08X, p2: 0x%08X, cc: %2u, lc: %2u, cmd: 0x%08X (%s)\n",
505 TileX(entry.tile), TileY(entry.tile), entry.p1, entry.p2, (uint) entry.current_company, (uint) entry.local_company, entry.cmd, GetCommandName(entry.cmd));
507 return buffer;
511 * This function range-checks a cmd, and checks if the cmd is not NULL
513 * @param cmd The integer value of a command
514 * @return true if the command is valid (and got a CommandProc function)
516 bool IsValidCommand(uint32 cmd)
518 cmd &= CMD_ID_MASK;
520 return cmd < lengthof(_command_proc_table) && _command_proc_table[cmd].proc != NULL;
524 * This function mask the parameter with CMD_ID_MASK and returns
525 * the flags which belongs to the given command.
527 * @param cmd The integer value of the command
528 * @return The flags for this command
530 CommandFlags GetCommandFlags(uint32 cmd)
532 assert(IsValidCommand(cmd));
534 return _command_proc_table[cmd & CMD_ID_MASK].flags;
538 * This function mask the parameter with CMD_ID_MASK and returns
539 * the name which belongs to the given command.
541 * @param cmd The integer value of the command
542 * @return The name for this command
544 const char *GetCommandName(uint32 cmd)
546 assert(IsValidCommand(cmd));
548 return _command_proc_table[cmd & CMD_ID_MASK].name;
552 * Returns whether the command is allowed while the game is paused.
553 * @param cmd The command to check.
554 * @return True if the command is allowed while paused, false otherwise.
556 bool IsCommandAllowedWhilePaused(uint32 cmd)
558 /* Lookup table for the command types that are allowed for a given pause level setting. */
559 static const int command_type_lookup[] = {
560 CMDPL_ALL_ACTIONS, ///< CMDT_LANDSCAPE_CONSTRUCTION
561 CMDPL_NO_LANDSCAPING, ///< CMDT_VEHICLE_CONSTRUCTION
562 CMDPL_NO_LANDSCAPING, ///< CMDT_MONEY_MANAGEMENT
563 CMDPL_NO_CONSTRUCTION, ///< CMDT_VEHICLE_MANAGEMENT
564 CMDPL_NO_CONSTRUCTION, ///< CMDT_ROUTE_MANAGEMENT
565 CMDPL_NO_CONSTRUCTION, ///< CMDT_OTHER_MANAGEMENT
566 CMDPL_NO_CONSTRUCTION, ///< CMDT_COMPANY_SETTING
567 CMDPL_NO_ACTIONS, ///< CMDT_SERVER_SETTING
568 CMDPL_NO_ACTIONS, ///< CMDT_CHEAT
570 assert_compile(lengthof(command_type_lookup) == CMDT_END);
572 assert(IsValidCommand(cmd));
573 return _game_mode == GM_EDITOR || command_type_lookup[_command_proc_table[cmd & CMD_ID_MASK].type] <= _settings_game.construction.command_pause_level;
577 static int _docommand_recursive = 0;
580 * Shorthand for calling the long DoCommand with a container.
582 * @param container Container with (almost) all information
583 * @param flags Flags for the command and how to execute the command
584 * @see CommandProc
585 * @return the cost
587 CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
589 return DoCommand(container->tile, container->p1, container->p2, flags, container->cmd & CMD_ID_MASK, container->text);
593 * This function executes a given command with the parameters from the #CommandProc parameter list.
594 * Depending on the flags parameter it execute or test a command.
596 * @param tile The tile to apply the command on (for the #CommandProc)
597 * @param p1 Additional data for the command (for the #CommandProc)
598 * @param p2 Additional data for the command (for the #CommandProc)
599 * @param flags Flags for the command and how to execute the command
600 * @param cmd The command-id to execute (a value of the CMD_* enums)
601 * @param text The text to pass
602 * @see CommandProc
603 * @return the cost
605 CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text)
607 CommandCost res;
609 /* Do not even think about executing out-of-bounds tile-commands */
610 if (tile != 0 && (tile >= MapSize() || (!IsValidTile(tile) && (flags & DC_ALL_TILES) == 0))) return CMD_ERROR;
612 /* Chop of any CMD_MSG or other flags; we don't need those here */
613 CommandProc *proc = _command_proc_table[cmd & CMD_ID_MASK].proc;
615 _docommand_recursive++;
617 /* only execute the test call if it's toplevel, or we're not execing. */
618 if (_docommand_recursive == 1 || !(flags & DC_EXEC) ) {
619 if (_docommand_recursive == 1) _cleared_object_areas.Clear();
620 SetTownRatingTestMode(true);
621 res = proc(tile, flags & ~DC_EXEC, p1, p2, text);
622 SetTownRatingTestMode(false);
623 if (res.Failed()) {
624 goto error;
627 if (_docommand_recursive == 1 &&
628 !(flags & DC_QUERY_COST) &&
629 !(flags & DC_BANKRUPT) &&
630 !CheckCompanyHasMoney(res)) { // CheckCompanyHasMoney() modifies 'res' to an error if it fails.
631 goto error;
634 if (!(flags & DC_EXEC)) {
635 _docommand_recursive--;
636 return res;
640 /* Execute the command here. All cost-relevant functions set the expenses type
641 * themselves to the cost object at some point */
642 if (_docommand_recursive == 1) _cleared_object_areas.Clear();
643 res = proc(tile, flags, p1, p2, text);
644 if (res.Failed()) {
645 error:
646 _docommand_recursive--;
647 return res;
650 /* if toplevel, subtract the money. */
651 if (--_docommand_recursive == 0 && !(flags & DC_BANKRUPT)) {
652 SubtractMoneyFromCompany(res);
655 return res;
659 * This functions returns the money which can be used to execute a command.
660 * This is either the money of the current company or INT64_MAX if there
661 * is no such a company "at the moment" like the server itself.
663 * @return The available money of a company or INT64_MAX
665 Money GetAvailableMoneyForCommand()
667 CompanyID company = _current_company;
668 if (!Company::IsValidID(company)) return INT64_MAX;
669 return Company::Get(company)->money;
673 * Shortcut for the long DoCommandP when having a container with the data.
674 * @param container the container with information.
675 * @param my_cmd indicator if the command is from a company or server (to display error messages for a user)
676 * @return true if the command succeeded, else false
678 bool DoCommandP(const CommandContainer *container, bool my_cmd)
680 return DoCommandP(container->tile, container->p1, container->p2, container->cmd, container->callback, container->text, my_cmd);
684 * Toplevel network safe docommand function for the current company. Must not be called recursively.
685 * The callback is called when the command succeeded or failed. The parameters
686 * \a tile, \a p1, and \a p2 are from the #CommandProc function. The parameter \a cmd is the command to execute.
687 * The parameter \a my_cmd is used to indicate if the command is from a company or the server.
689 * @param tile The tile to perform a command on (see #CommandProc)
690 * @param p1 Additional data for the command (see #CommandProc)
691 * @param p2 Additional data for the command (see #CommandProc)
692 * @param cmd The command to execute (a CMD_* value)
693 * @param callback A callback function to call after the command is finished
694 * @param text The text to pass
695 * @param my_cmd indicator if the command is from a company or server (to display error messages for a user)
696 * @param binary_length The quantity of binary data in text
697 * @return \c true if the command succeeded, else \c false.
699 bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd, uint32 binary_length)
701 /* Cost estimation is generally only done when the
702 * local user presses shift while constructing somthing.
703 * However, in case of incoming network commands or
704 * map generation we do want to execute. */
705 bool estimate_only = false;
706 switch (_command_proc_table[cmd & CMD_ID_MASK].type) {
707 case CMDT_LANDSCAPE_CONSTRUCTION:
708 case CMDT_VEHICLE_CONSTRUCTION:
709 estimate_only = _shift_pressed && IsLocalCompany() &&
710 !_generating_world && !(cmd & CMD_NETWORK_COMMAND);
711 break;
713 default:
714 break; // just to silence warnings
718 /* We're only sending the command, so don't do
719 * fancy things for 'success'. */
720 bool only_sending = _networking && !(cmd & CMD_NETWORK_COMMAND);
722 /* Where to show the message? */
723 int x = TileX(tile) * TILE_SIZE;
724 int y = TileY(tile) * TILE_SIZE;
726 if (_pause_mode != PM_UNPAUSED && !IsCommandAllowedWhilePaused(cmd)) {
727 ShowErrorMessage(GB(cmd, 16, 16), STR_ERROR_NOT_ALLOWED_WHILE_PAUSED, WL_INFO, x, y);
728 return false;
731 #ifdef ENABLE_NETWORK
732 /* Only set p2 when the command does not come from the network. */
733 if (!(cmd & CMD_NETWORK_COMMAND) && GetCommandFlags(cmd) & CMD_CLIENT_ID && p2 == 0) p2 = CLIENT_ID_SERVER;
734 #endif
736 CommandCost res = DoCommandPInternal(tile, p1, p2, cmd, callback, text, my_cmd, estimate_only, binary_length);
737 if (res.Failed()) {
738 /* Only show the error when it's for us. */
739 StringID error_part1 = GB(cmd, 16, 16);
740 if (estimate_only || (IsLocalCompany() && error_part1 != 0 && my_cmd)) {
741 ShowErrorMessage(error_part1, res.GetErrorMessage(), WL_INFO, x, y, res.GetTextRefStackGRF(), res.GetTextRefStackSize(), res.GetTextRefStack());
743 } else if (estimate_only) {
744 ShowEstimatedCostOrIncome(res.GetCost(), x, y);
745 } else if (!only_sending && res.GetCost() != 0 && tile != 0 && IsLocalCompany() && _game_mode != GM_EDITOR) {
746 /* Only show the cost animation when we did actually
747 * execute the command, i.e. we're not sending it to
748 * the server, when it has cost the local company
749 * something. Furthermore in the editor there is no
750 * concept of cost, so don't show it there either. */
751 ShowCostOrIncomeAnimation(x, y, GetSlopePixelZ(x, y), res.GetCost());
754 if (!estimate_only && !only_sending && callback != NULL) {
755 callback(res, tile, p1, p2);
758 CommandLogEntryFlag log_flags;
759 log_flags = CLEF_NONE;
760 if (!StrEmpty(text)) log_flags |= CLEF_TEXT;
761 if (estimate_only) log_flags |= CLEF_ESTIMATE_ONLY;
762 if (only_sending) log_flags |= CLEF_ONLY_SENDING;
763 if (my_cmd) log_flags |= CLEF_MY_CMD;
764 command_log[command_log_next] = CommandLogEntry(res, tile, p1, p2, cmd, log_flags);
765 command_log_next = (command_log_next + 1) % command_log.size();
766 command_log_count++;
768 return res.Succeeded();
773 * Helper to deduplicate the code for returning.
774 * @param cmd the command cost to return.
775 * @param clear whether to keep the storage changes or not.
777 #define return_dcpi(cmd) { _docommand_recursive = 0; return cmd; }
780 * Helper function for the toplevel network safe docommand function for the current company.
782 * @param tile The tile to perform a command on (see #CommandProc)
783 * @param p1 Additional data for the command (see #CommandProc)
784 * @param p2 Additional data for the command (see #CommandProc)
785 * @param cmd The command to execute (a CMD_* value)
786 * @param callback A callback function to call after the command is finished
787 * @param text The text to pass
788 * @param my_cmd indicator if the command is from a company or server (to display error messages for a user)
789 * @param estimate_only whether to give only the estimate or also execute the command
790 * @return the command cost of this function.
792 CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd, bool estimate_only, uint32 binary_length)
794 /* Prevent recursion; it gives a mess over the network */
795 assert(_docommand_recursive == 0);
796 _docommand_recursive = 1;
798 /* Reset the state. */
799 _additional_cash_required = 0;
801 /* Get pointer to command handler */
802 byte cmd_id = cmd & CMD_ID_MASK;
803 assert(cmd_id < lengthof(_command_proc_table));
805 CommandProc *proc = _command_proc_table[cmd_id].proc;
806 /* Shouldn't happen, but you never know when someone adds
807 * NULLs to the _command_proc_table. */
808 assert(proc != NULL);
810 /* Command flags are used internally */
811 CommandFlags cmd_flags = GetCommandFlags(cmd);
812 /* Flags get send to the DoCommand */
813 DoCommandFlag flags = CommandFlagsToDCFlags(cmd_flags);
815 #ifdef ENABLE_NETWORK
816 /* Make sure p2 is properly set to a ClientID. */
817 assert(!(cmd_flags & CMD_CLIENT_ID) || p2 != 0);
818 #endif
820 /* Do not even think about executing out-of-bounds tile-commands */
821 if (tile != 0 && (tile >= MapSize() || (!IsValidTile(tile) && (cmd_flags & CMD_ALL_TILES) == 0))) return_dcpi(CMD_ERROR);
823 /* Always execute server and spectator commands as spectator */
824 bool exec_as_spectator = (cmd_flags & (CMD_SPECTATOR | CMD_SERVER)) != 0;
826 /* If the company isn't valid it may only do server command or start a new company!
827 * The server will ditch any server commands a client sends to it, so effectively
828 * this guards the server from executing functions for an invalid company. */
829 if (_game_mode == GM_NORMAL && !exec_as_spectator && !Company::IsValidID(_current_company) && !(_current_company == OWNER_DEITY && (cmd_flags & CMD_DEITY) != 0)) {
830 return_dcpi(CMD_ERROR);
833 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
834 if (exec_as_spectator) cur_company.Change(COMPANY_SPECTATOR);
836 bool test_and_exec_can_differ = (cmd_flags & CMD_NO_TEST) != 0;
838 /* Test the command. */
839 _cleared_object_areas.Clear();
840 SetTownRatingTestMode(true);
841 BasePersistentStorageArray::SwitchMode(PSM_ENTER_TESTMODE);
842 CommandCost res = proc(tile, flags, p1, p2, text);
843 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_TESTMODE);
844 SetTownRatingTestMode(false);
846 /* Make sure we're not messing things up here. */
847 assert(exec_as_spectator ? _current_company == COMPANY_SPECTATOR : cur_company.Verify());
849 /* If the command fails, we're doing an estimate
850 * or the player does not have enough money
851 * (unless it's a command where the test and
852 * execution phase might return different costs)
853 * we bail out here. */
854 if (res.Failed() || estimate_only ||
855 (!test_and_exec_can_differ && !CheckCompanyHasMoney(res))) {
856 if (!_networking || _generating_world || (cmd & CMD_NETWORK_COMMAND) != 0) {
857 /* Log the failed command as well. Just to be able to be find
858 * causes of desyncs due to bad command test implementations. */
859 DEBUG(desync, 1, "cmdf: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text, GetCommandName(cmd));
861 cur_company.Restore();
862 return_dcpi(res);
865 #ifdef ENABLE_NETWORK
867 * If we are in network, and the command is not from the network
868 * send it to the command-queue and abort execution
870 if (_networking && !_generating_world && !(cmd & CMD_NETWORK_COMMAND)) {
871 NetworkSendCommand(tile, p1, p2, cmd & ~CMD_FLAGS_MASK, callback, text, _current_company, binary_length);
872 cur_company.Restore();
874 /* Don't return anything special here; no error, no costs.
875 * This way it's not handled by DoCommand and only the
876 * actual execution of the command causes messages. Also
877 * reset the storages as we've not executed the command. */
878 return_dcpi(CommandCost());
880 #endif /* ENABLE_NETWORK */
881 DEBUG(desync, 1, "cmd: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text, GetCommandName(cmd));
883 /* Actually try and execute the command. If no cost-type is given
884 * use the construction one */
885 _cleared_object_areas.Clear();
886 BasePersistentStorageArray::SwitchMode(PSM_ENTER_COMMAND);
887 CommandCost res2 = proc(tile, flags | DC_EXEC, p1, p2, text);
888 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_COMMAND);
890 if (cmd_id == CMD_COMPANY_CTRL) {
891 cur_company.Trash();
892 /* We are a new company -> Switch to new local company.
893 * We were closed down -> Switch to spectator
894 * Some other company opened/closed down -> The outside function will switch back */
895 _current_company = _local_company;
896 } else {
897 /* Make sure nothing bad happened, like changing the current company. */
898 assert(exec_as_spectator ? _current_company == COMPANY_SPECTATOR : cur_company.Verify());
899 cur_company.Restore();
902 /* If the test and execution can differ we have to check the
903 * return of the command. Otherwise we can check whether the
904 * test and execution have yielded the same result,
905 * i.e. cost and error state are the same. */
906 if (!test_and_exec_can_differ) {
907 assert(res.GetCost() == res2.GetCost() && res.Failed() == res2.Failed()); // sanity check
908 } else if (res2.Failed()) {
909 return_dcpi(res2);
912 /* If we're needing more money and we haven't done
913 * anything yet, ask for the money! */
914 if (_additional_cash_required != 0 && res2.GetCost() == 0) {
915 /* It could happen we removed rail, thus gained money, and deleted something else.
916 * So make sure the signal buffer is empty even in this case */
917 UpdateSignalsInBuffer();
918 SetDParam(0, _additional_cash_required);
919 return_dcpi(CommandCost(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY));
922 /* update last build coordinate of company. */
923 if (tile != 0) {
924 Company *c = Company::GetIfValid(_current_company);
925 if (c != NULL) c->last_build_coordinate = tile;
928 SubtractMoneyFromCompany(res2);
930 /* update signals if needed */
931 UpdateSignalsInBuffer();
933 return_dcpi(res2);
935 #undef return_dcpi
939 * Adds the cost of the given command return value to this cost.
940 * Also takes a possible error message when it is set.
941 * @param ret The command to add the cost of.
943 void CommandCost::AddCost(const CommandCost &ret)
945 this->AddCost(ret.cost);
946 if (this->success && !ret.success) {
947 this->message = ret.message;
948 this->success = false;
953 * Values to put on the #TextRefStack for the error message.
954 * There is only one static instance of the array, just like there is only one
955 * instance of normal DParams.
957 uint32 CommandCost::textref_stack[16];
960 * Activate usage of the NewGRF #TextRefStack for the error message.
961 * @param grffile NewGRF that provides the #TextRefStack
962 * @param num_registers number of entries to copy from the temporary NewGRF registers
964 void CommandCost::UseTextRefStack(const GRFFile *grffile, uint num_registers)
966 extern TemporaryStorageArray<int32, 0x110> _temp_store;
968 assert(num_registers < lengthof(textref_stack));
969 this->textref_stack_grffile = grffile;
970 this->textref_stack_size = num_registers;
971 for (uint i = 0; i < num_registers; i++) {
972 textref_stack[i] = _temp_store.GetValue(0x100 + i);