OpenTTD Source: src/misc_cmd.cpp Source File

OpenTTD Source 15.0-RC2

misc_cmd.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "command_func.h"
12#include "economy_func.h"
13#include "window_func.h"
14#include "textbuf_gui.h"
15#include "network/network.h"
16#include "network/network_func.h"
17#include "strings_func.h"
18#include "company_func.h"
19#include "company_gui.h"
20#include "company_base.h"
21#include "tile_map.h"
22#include "texteff.hpp"
23#include "core/backup_type.hpp"
24#include "misc_cmd.h"
25
26#include "table/strings.h"
27
28#include "safeguards.h"
29
39 CommandCost CmdIncreaseLoan(DoCommandFlags flags, LoanCommand cmd, Money amount)
40{
41 Company *c = Company::Get(_current_company);
42 Money max_loan = c->GetMaxLoan();
43 if (c->current_loan >= max_loan) {
44 return CommandCostWithParam(STR_ERROR_MAXIMUM_PERMITTED_LOAN, max_loan);
45 }
46
47 Money loan;
48 switch (cmd) {
49 default: return CMD_ERROR; // Invalid method
50 case LoanCommand::Interval: // Take some extra loan
51 loan = LOAN_INTERVAL;
52 break;
53 case LoanCommand::Max: // Take a loan as big as possible
54 loan = max_loan - c->current_loan;
55 break;
56 case LoanCommand::Amount: // Take the given amount of loan
57 loan = amount;
58 if (loan < LOAN_INTERVAL || c->current_loan + loan > max_loan || loan % LOAN_INTERVAL != 0) return CMD_ERROR;
59 break;
60 }
61
62 /* In case adding the loan triggers the overflow protection of Money,
63 * we would essentially be losing money as taking and repaying the loan
64 * immediately would not get us back to the same bank balance anymore. */
65 if (c->money > Money::max() - loan) return CMD_ERROR;
66
67 if (flags.Test(DoCommandFlag::Execute)) {
68 c->money += loan;
69 c->current_loan += loan;
70 InvalidateCompanyWindows(c);
71 }
72
73 return CommandCost(EXPENSES_OTHER);
74}
75
85 CommandCost CmdDecreaseLoan(DoCommandFlags flags, LoanCommand cmd, Money amount)
86{
87 Company *c = Company::Get(_current_company);
88
89 if (c->current_loan == 0) return CommandCost(STR_ERROR_LOAN_ALREADY_REPAID);
90
91 Money loan;
92 switch (cmd) {
93 default: return CMD_ERROR; // Invalid method
94 case LoanCommand::Interval: // Pay back one step
95 loan = std::min(c->current_loan, (Money)LOAN_INTERVAL);
96 break;
97 case LoanCommand::Max: // Pay back as much as possible
98 loan = std::max(std::min(c->current_loan, GetAvailableMoneyForCommand()), (Money)LOAN_INTERVAL);
99 loan -= loan % LOAN_INTERVAL;
100 break;
101 case LoanCommand::Amount: // Repay the given amount of loan
102 loan = amount;
103 if (loan % LOAN_INTERVAL != 0 || loan < LOAN_INTERVAL || loan > c->current_loan) return CMD_ERROR; // Invalid amount to loan
104 break;
105 }
106
107 if (GetAvailableMoneyForCommand() < loan) {
108 return CommandCostWithParam(STR_ERROR_CURRENCY_REQUIRED, loan);
109 }
110
111 if (flags.Test(DoCommandFlag::Execute)) {
112 c->money -= loan;
113 c->current_loan -= loan;
114 InvalidateCompanyWindows(c);
115 }
116 return CommandCost();
117}
118
125 CommandCost CmdSetCompanyMaxLoan(DoCommandFlags flags, CompanyID company, Money amount)
126{
127 if (_current_company != OWNER_DEITY) return CMD_ERROR;
128 if (amount != COMPANY_MAX_LOAN_DEFAULT) {
129 if (amount < 0 || amount > (Money)MAX_LOAN_LIMIT) return CMD_ERROR;
130 }
131
132 Company *c = Company::GetIfValid(company);
133 if (c == nullptr) return CMD_ERROR;
134
135 if (flags.Test(DoCommandFlag::Execute)) {
136 /* Round the amount down to a multiple of LOAN_INTERVAL. */
137 if (amount != COMPANY_MAX_LOAN_DEFAULT) amount -= (int64_t)amount % LOAN_INTERVAL;
138
139 c->max_loan = amount;
140 InvalidateCompanyWindows(c);
141 }
142 return CommandCost();
143}
144
150 static void AskUnsafeUnpauseCallback(Window *, bool confirmed)
151{
152 if (confirmed) {
153 Command<CMD_PAUSE>::Post(PauseMode::Error, false);
154 }
155}
156
167 CommandCost CmdPause(DoCommandFlags flags, PauseMode mode, bool pause)
168{
169 switch (mode) {
170 case PauseMode::SaveLoad:
171 case PauseMode::Error:
172 case PauseMode::Normal:
173 case PauseMode::GameScript:
174 case PauseMode::LinkGraph:
175 break;
176
177 case PauseMode::Join:
178 case PauseMode::ActiveClients:
179 if (!_networking) return CMD_ERROR;
180 break;
181
182 default: return CMD_ERROR;
183 }
184 if (flags.Test(DoCommandFlag::Execute)) {
185 if (mode == PauseMode::Normal && _pause_mode.Test(PauseMode::Error)) {
186 ShowQuery(
187 GetEncodedString(STR_NEWGRF_UNPAUSE_WARNING_TITLE),
188 GetEncodedString(STR_NEWGRF_UNPAUSE_WARNING),
189 nullptr,
190 AskUnsafeUnpauseCallback
191 );
192 } else {
193 PauseModes prev_mode = _pause_mode;
194
195 if (pause) {
196 _pause_mode.Set(mode);
197 } else {
198 _pause_mode.Reset(mode);
199
200 /* If the only remaining reason to be paused is that we saw a command during pause, unpause. */
201 if (_pause_mode == PauseMode::CommandDuringPause) {
202 _pause_mode = {};
203 }
204 }
205
206 NetworkHandlePauseChange(prev_mode, mode);
207 }
208
209 SetWindowDirty(WC_STATUS_BAR, 0);
210 SetWindowDirty(WC_MAIN_TOOLBAR, 0);
211 }
212 return CommandCost();
213}
214
220 CommandCost CmdMoneyCheat(DoCommandFlags, Money amount)
221{
222 return CommandCost(EXPENSES_OTHER, -amount);
223}
224
234 CommandCost CmdChangeBankBalance(DoCommandFlags flags, TileIndex tile, Money delta, CompanyID company, ExpensesType expenses_type)
235{
236 if (!Company::IsValidID(company)) return CMD_ERROR;
237 if (expenses_type >= EXPENSES_END) return CMD_ERROR;
238 if (_current_company != OWNER_DEITY) return CMD_ERROR;
239
240 if (flags.Test(DoCommandFlag::Execute)) {
241 /* Change company bank balance of company. */
242 Backup<CompanyID> cur_company(_current_company, company);
243 SubtractMoneyFromCompany(CommandCost(expenses_type, -delta));
244 cur_company.Restore();
245
246 if (tile != 0) {
247 ShowCostOrIncomeAnimation(TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE, GetTilePixelZ(tile), -delta);
248 }
249 }
250
251 /* This command doesn't cost anything for deity. */
252 CommandCost zero_cost(expenses_type, (Money)0);
253 return zero_cost;
254}
backup_type.hpp
Class for backupping variables and making sure they are restored later.
BaseBitSet::Test
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Definition base_bitset_type.hpp:141
BaseBitSet::Reset
constexpr Timpl & Reset()
Reset all bits.
Definition base_bitset_type.hpp:83
BaseBitSet::Set
constexpr Timpl & Set()
Set all bits.
Definition base_bitset_type.hpp:40
CommandCost
Common return value for all commands.
Definition command_type.h:24
EnumBitSet
Enum-as-bit-set wrapper.
Definition enum_type.hpp:177
OverflowSafeInt< int64_t >
CommandCostWithParam
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:417
command_func.h
Functions related to commands.
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition command_func.h:28
DoCommandFlag::Execute
@ Execute
execute the given command
company_base.h
Definition of stuff that is very close to a company, like the company struct itself.
InvalidateCompanyWindows
void InvalidateCompanyWindows(const Company *company)
Mark all finance windows owned by a company as needing a refresh.
Definition company_cmd.cpp:206
GetAvailableMoneyForCommand
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
Definition company_cmd.cpp:252
SubtractMoneyFromCompany
void SubtractMoneyFromCompany(const CommandCost &cost)
Subtract money from the _current_company, if the company is valid.
Definition company_cmd.cpp:313
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:56
company_func.h
Functions related to companies.
company_gui.h
GUI Functions related to companies.
OWNER_DEITY
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
Definition company_type.h:28
economy_func.h
Functions related to the economy.
MAX_LOAN_LIMIT
static const int64_t MAX_LOAN_LIMIT
The max amount possible to configure for a max loan of a company.
Definition economy_type.h:215
ExpensesType
ExpensesType
Types of expenses.
Definition economy_type.h:178
EXPENSES_END
@ EXPENSES_END
Number of expense types.
Definition economy_type.h:192
EXPENSES_OTHER
@ EXPENSES_OTHER
Other expenses.
Definition economy_type.h:191
LOAN_INTERVAL
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
Definition economy_type.h:211
_pause_mode
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:50
TileY
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:437
TileX
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:427
CmdChangeBankBalance
CommandCost CmdChangeBankBalance(DoCommandFlags flags, TileIndex tile, Money delta, CompanyID company, ExpensesType expenses_type)
Change the bank bank balance of a company by inserting or removing money without affecting the loan.
Definition misc_cmd.cpp:234
CmdDecreaseLoan
CommandCost CmdDecreaseLoan(DoCommandFlags flags, LoanCommand cmd, Money amount)
Decrease the loan of your company.
Definition misc_cmd.cpp:85
CmdIncreaseLoan
CommandCost CmdIncreaseLoan(DoCommandFlags flags, LoanCommand cmd, Money amount)
Increase the loan of your company.
Definition misc_cmd.cpp:39
CmdMoneyCheat
CommandCost CmdMoneyCheat(DoCommandFlags, Money amount)
Change the financial flow of your company.
Definition misc_cmd.cpp:220
CmdPause
CommandCost CmdPause(DoCommandFlags flags, PauseMode mode, bool pause)
Pause/Unpause the game (server-only).
Definition misc_cmd.cpp:167
CmdSetCompanyMaxLoan
CommandCost CmdSetCompanyMaxLoan(DoCommandFlags flags, CompanyID company, Money amount)
Sets the max loan amount of your company.
Definition misc_cmd.cpp:125
AskUnsafeUnpauseCallback
static void AskUnsafeUnpauseCallback(Window *, bool confirmed)
In case of an unsafe unpause, we want the user to confirm that it might crash.
Definition misc_cmd.cpp:150
misc_cmd.h
Miscellaneous command definitions.
ShowQuery
void ShowQuery(EncodedString &&caption, EncodedString &&message, Window *parent, QueryCallbackProc *callback, bool focus)
Show a confirmation window with standard 'yes' and 'no' buttons The window is aligned to the centre o...
Definition misc_gui.cpp:1202
ShowCostOrIncomeAnimation
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition misc_gui.cpp:513
NetworkHandlePauseChange
void NetworkHandlePauseChange(PauseModes prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
Definition network.cpp:351
_networking
bool _networking
are we in networking mode?
Definition network.cpp:66
network.h
Basic functions/variables used all over the place.
network_func.h
Network functions used by other parts of OpenTTD.
PauseMode
PauseMode
Modes of pausing we've got.
Definition openttd.h:68
PauseMode::LinkGraph
@ LinkGraph
A game paused due to the link graph schedule lagging.
PauseMode::Error
@ Error
A game paused because a (critical) error.
PauseMode::GameScript
@ GameScript
A game paused by a game script.
PauseMode::ActiveClients
@ ActiveClients
A game paused for 'min_active_clients'.
PauseMode::Normal
@ Normal
A game normally paused.
PauseMode::Join
@ Join
A game paused for 'pause_on_join'.
PauseMode::CommandDuringPause
@ CommandDuringPause
A game paused, and a command executed during the pause; resets on autosave.
PauseMode::SaveLoad
@ SaveLoad
A game paused for saving/loading.
safeguards.h
A number of safeguards to prevent using unsafe methods.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
GetEncodedString
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
strings_func.h
Functions related to OTTD's strings.
Backup
Class to backup a specific variable and restore it later.
Definition backup_type.hpp:21
Backup::Restore
void Restore()
Restore the variable.
Definition backup_type.hpp:110
CommandHelper
Definition command_func.h:83
CompanyProperties::current_loan
Money current_loan
Amount of money borrowed from the bank.
Definition company_base.h:86
CompanyProperties::max_loan
Money max_loan
Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
Definition company_base.h:87
CompanyProperties::money
Money money
Money owned by the company.
Definition company_base.h:84
Company
Definition company_base.h:127
Company::GetMaxLoan
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
Definition company_cmd.cpp:107
PoolID< uint8_t, struct CompanyIDTag, 0xF, 0xFF >
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Definition pool_type.hpp:398
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
Window
Data structure for an opened window.
Definition window_gui.h:274
textbuf_gui.h
Stuff related to the text buffer GUI.
texteff.hpp
Functions related to text effects.
tile_map.h
Map writing/reading functions for tiles.
GetTilePixelZ
int GetTilePixelZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.h:302
TILE_SIZE
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3176
window_func.h
Window functions not directly related to making/drawing windows.
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition window_type.h:69
WC_MAIN_TOOLBAR
@ WC_MAIN_TOOLBAR
Main toolbar (the long bar at the top); Window numbers:
Definition window_type.h:63