Feature: Build objects by area
[openttd-github.git] / src / company_cmd.cpp
blob681912f17c9ebb25ae25e1437126127646820dc5
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 <http://www.gnu.org/licenses/>.
6 */
8 /** @file company_cmd.cpp Handling of companies. */
10 #include "stdafx.h"
11 #include "company_base.h"
12 #include "company_func.h"
13 #include "company_gui.h"
14 #include "core/backup_type.hpp"
15 #include "town.h"
16 #include "news_func.h"
17 #include "command_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "network/network_base.h"
21 #include "network/network_admin.h"
22 #include "ai/ai.hpp"
23 #include "company_manager_face.h"
24 #include "window_func.h"
25 #include "strings_func.h"
26 #include "date_func.h"
27 #include "sound_func.h"
28 #include "rail.h"
29 #include "core/pool_func.hpp"
30 #include "settings_func.h"
31 #include "vehicle_base.h"
32 #include "vehicle_func.h"
33 #include "smallmap_gui.h"
34 #include "game/game.hpp"
35 #include "goal_base.h"
36 #include "story_base.h"
37 #include "widgets/statusbar_widget.h"
38 #include "company_cmd.h"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 void ClearEnginesHiddenFlagOfCompany(CompanyID cid);
46 CompanyID _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
47 CompanyID _current_company; ///< Company currently doing an action.
48 Colours _company_colours[MAX_COMPANIES]; ///< NOSAVE: can be determined from company structs.
49 CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
50 uint _next_competitor_start; ///< the number of ticks before the next AI is started
51 uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
53 CompanyPool _company_pool("Company"); ///< Pool of companies.
54 INSTANTIATE_POOL_METHODS(Company)
56 /**
57 * Constructor.
58 * @param name_1 Name of the company.
59 * @param is_ai A computer program is running for this company.
61 Company::Company(uint16 name_1, bool is_ai)
63 this->name_1 = name_1;
64 this->location_of_HQ = INVALID_TILE;
65 this->is_ai = is_ai;
66 this->terraform_limit = (uint32)_settings_game.construction.terraform_frame_burst << 16;
67 this->clear_limit = (uint32)_settings_game.construction.clear_frame_burst << 16;
68 this->tree_limit = (uint32)_settings_game.construction.tree_frame_burst << 16;
69 this->build_object_limit = (uint32)_settings_game.construction.build_object_frame_burst << 16;
71 std::fill(this->share_owners.begin(), this->share_owners.end(), INVALID_OWNER);
72 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
75 /** Destructor. */
76 Company::~Company()
78 if (CleaningPool()) return;
80 CloseCompanyWindows(this->index);
83 /**
84 * Invalidating some stuff after removing item from the pool.
85 * @param index index of deleted item
87 void Company::PostDestructor(size_t index)
89 InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
90 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
91 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
92 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
93 /* If the currently shown error message has this company in it, then close it. */
94 InvalidateWindowData(WC_ERRMSG, 0);
97 /**
98 * Sets the local company and updates the settings that are set on a
99 * per-company basis to reflect the core's state in the GUI.
100 * @param new_company the new company
101 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
103 void SetLocalCompany(CompanyID new_company)
105 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
106 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
108 /* If actually changing to another company, several windows need closing */
109 bool switching_company = _local_company != new_company;
111 /* Delete the chat window, if you were team chatting. */
112 if (switching_company) InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
114 assert(IsLocalCompany());
116 _current_company = _local_company = new_company;
118 /* Delete any construction windows... */
119 if (switching_company) CloseConstructionWindows();
121 /* ... and redraw the whole screen. */
122 MarkWholeScreenDirty();
123 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
124 InvalidateWindowClassesData(WC_GOALS_LIST);
128 * Get the colour for DrawString-subroutines which matches the colour of the company.
129 * @param company Company to get the colour of.
130 * @return Colour of \a company.
132 TextColour GetDrawStringCompanyColour(CompanyID company)
134 if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
135 return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
139 * Draw the icon of a company.
140 * @param c Company that needs its icon drawn.
141 * @param x Horizontal coordinate of the icon.
142 * @param y Vertical coordinate of the icon.
144 void DrawCompanyIcon(CompanyID c, int x, int y)
146 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
150 * Checks whether a company manager's face is a valid encoding.
151 * Unused bits are not enforced to be 0.
152 * @param cmf the fact to check
153 * @return true if and only if the face is valid
155 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
157 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
159 GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
160 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
161 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
162 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
164 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
165 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
166 switch (cmfv) {
167 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
168 case CMFV_LIPS:
169 case CMFV_NOSE: if (has_moustache) continue; break;
170 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
171 case CMFV_GLASSES: if (!has_glasses) continue; break;
172 default: break;
174 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
177 return true;
181 * Refresh all windows owned by a company.
182 * @param company Company that changed, and needs its windows refreshed.
184 void InvalidateCompanyWindows(const Company *company)
186 CompanyID cid = company->index;
188 if (cid == _local_company) SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_RIGHT);
189 SetWindowDirty(WC_FINANCES, cid);
193 * Verify whether the company can pay the bill.
194 * @param[in,out] cost Money to pay, is changed to an error if the company does not have enough money.
195 * @return Function returns \c true if the company has enough money, else it returns \c false.
197 bool CheckCompanyHasMoney(CommandCost &cost)
199 if (cost.GetCost() > 0) {
200 const Company *c = Company::GetIfValid(_current_company);
201 if (c != nullptr && cost.GetCost() > c->money) {
202 SetDParam(0, cost.GetCost());
203 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
204 return false;
207 return true;
211 * Deduct costs of a command from the money of a company.
212 * @param c Company to pay the bill.
213 * @param cost Money to pay.
215 static void SubtractMoneyFromAnyCompany(Company *c, const CommandCost &cost)
217 if (cost.GetCost() == 0) return;
218 assert(cost.GetExpensesType() != INVALID_EXPENSES);
220 c->money -= cost.GetCost();
221 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
223 if (HasBit(1 << EXPENSES_TRAIN_REVENUE |
224 1 << EXPENSES_ROADVEH_REVENUE |
225 1 << EXPENSES_AIRCRAFT_REVENUE |
226 1 << EXPENSES_SHIP_REVENUE, cost.GetExpensesType())) {
227 c->cur_economy.income -= cost.GetCost();
228 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
229 1 << EXPENSES_ROADVEH_RUN |
230 1 << EXPENSES_AIRCRAFT_RUN |
231 1 << EXPENSES_SHIP_RUN |
232 1 << EXPENSES_PROPERTY |
233 1 << EXPENSES_LOAN_INTEREST, cost.GetExpensesType())) {
234 c->cur_economy.expenses -= cost.GetCost();
237 InvalidateCompanyWindows(c);
241 * Subtract money from the #_current_company, if the company is valid.
242 * @param cost Money to pay.
244 void SubtractMoneyFromCompany(const CommandCost &cost)
246 Company *c = Company::GetIfValid(_current_company);
247 if (c != nullptr) SubtractMoneyFromAnyCompany(c, cost);
251 * Subtract money from a company, including the money fraction.
252 * @param company Company paying the bill.
253 * @param cst Cost of a command.
255 void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
257 Company *c = Company::Get(company);
258 byte m = c->money_fraction;
259 Money cost = cst.GetCost();
261 c->money_fraction = m - (byte)cost;
262 cost >>= 8;
263 if (c->money_fraction > m) cost++;
264 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
267 /** Update the landscaping limits per company. */
268 void UpdateLandscapingLimits()
270 for (Company *c : Company::Iterate()) {
271 c->terraform_limit = std::min<uint64>((uint64)c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint64)_settings_game.construction.terraform_frame_burst << 16);
272 c->clear_limit = std::min<uint64>((uint64)c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint64)_settings_game.construction.clear_frame_burst << 16);
273 c->tree_limit = std::min<uint64>((uint64)c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint64)_settings_game.construction.tree_frame_burst << 16);
274 c->build_object_limit = std::min<uint64>((uint64)c->build_object_limit + _settings_game.construction.build_object_per_64k_frames, (uint64)_settings_game.construction.build_object_frame_burst << 16);
279 * Set the right DParams to get the name of an owner.
280 * @param owner the owner to get the name of.
281 * @param tile optional tile to get the right town.
282 * @pre if tile == 0, then owner can't be OWNER_TOWN.
284 void GetNameOfOwner(Owner owner, TileIndex tile)
286 SetDParam(2, owner);
288 if (owner != OWNER_TOWN) {
289 if (!Company::IsValidID(owner)) {
290 SetDParam(0, STR_COMPANY_SOMEONE);
291 } else {
292 SetDParam(0, STR_COMPANY_NAME);
293 SetDParam(1, owner);
295 } else {
296 assert(tile != 0);
297 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
299 SetDParam(0, STR_TOWN_NAME);
300 SetDParam(1, t->index);
306 * Check whether the current owner owns something.
307 * If that isn't the case an appropriate error will be given.
308 * @param owner the owner of the thing to check.
309 * @param tile optional tile to get the right town.
310 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
311 * @return A succeeded command iff it's owned by the current company, else a failed command.
313 CommandCost CheckOwnership(Owner owner, TileIndex tile)
315 assert(owner < OWNER_END);
316 assert(owner != OWNER_TOWN || tile != 0);
318 if (owner == _current_company) return CommandCost();
320 GetNameOfOwner(owner, tile);
321 return_cmd_error(STR_ERROR_OWNED_BY);
325 * Check whether the current owner owns the stuff on
326 * the given tile. If that isn't the case an
327 * appropriate error will be given.
328 * @param tile the tile to check.
329 * @return A succeeded command iff it's owned by the current company, else a failed command.
331 CommandCost CheckTileOwnership(TileIndex tile)
333 Owner owner = GetTileOwner(tile);
335 assert(owner < OWNER_END);
337 if (owner == _current_company) return CommandCost();
339 /* no need to get the name of the owner unless we're the local company (saves some time) */
340 if (IsLocalCompany()) GetNameOfOwner(owner, tile);
341 return_cmd_error(STR_ERROR_OWNED_BY);
345 * Generate the name of a company from the last build coordinate.
346 * @param c Company to give a name.
348 static void GenerateCompanyName(Company *c)
350 /* Reserve space for extra unicode character. We need to do this to be able
351 * to detect too long company name. */
352 char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
354 if (c->name_1 != STR_SV_UNNAMED) return;
355 if (c->last_build_coordinate == 0) return;
357 Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
359 StringID str;
360 uint32 strp;
361 if (t->name.empty() && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
362 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
363 strp = t->townnameparts;
365 verify_name:;
366 /* No companies must have this name already */
367 for (const Company *cc : Company::Iterate()) {
368 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
371 GetString(buffer, str, lastof(buffer));
372 if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
374 set_name:;
375 c->name_1 = str;
376 c->name_2 = strp;
378 MarkWholeScreenDirty();
380 if (c->is_ai) {
381 CompanyNewsInformation *cni = new CompanyNewsInformation(c);
382 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
383 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
384 SetDParamStr(2, cni->company_name);
385 SetDParam(3, t->index);
386 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
388 return;
390 bad_town_name:;
392 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
393 str = SPECSTR_ANDCO_NAME;
394 strp = c->president_name_2;
395 goto set_name;
396 } else {
397 str = SPECSTR_ANDCO_NAME;
398 strp = Random();
399 goto verify_name;
403 /** Sorting weights for the company colours. */
404 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
405 /** Similar colours, so we can try to prevent same coloured companies. */
406 static const Colours _similar_colour[COLOUR_END][2] = {
407 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
408 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
409 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
410 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
411 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
412 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
413 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
414 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
415 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
416 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
417 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
418 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
419 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
420 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
421 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
422 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
426 * Generate a company colour.
427 * @return Generated company colour.
429 static Colours GenerateCompanyColour()
431 Colours colours[COLOUR_END];
433 /* Initialize array */
434 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
436 /* And randomize it */
437 for (uint i = 0; i < 100; i++) {
438 uint r = Random();
439 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
442 /* Bubble sort it according to the values in table 1 */
443 for (uint i = 0; i < COLOUR_END; i++) {
444 for (uint j = 1; j < COLOUR_END; j++) {
445 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
446 Swap(colours[j - 1], colours[j]);
451 /* Move the colours that look similar to each company's colour to the side */
452 for (const Company *c : Company::Iterate()) {
453 Colours pcolour = (Colours)c->colour;
455 for (uint i = 0; i < COLOUR_END; i++) {
456 if (colours[i] == pcolour) {
457 colours[i] = INVALID_COLOUR;
458 break;
462 for (uint j = 0; j < 2; j++) {
463 Colours similar = _similar_colour[pcolour][j];
464 if (similar == INVALID_COLOUR) break;
466 for (uint i = 1; i < COLOUR_END; i++) {
467 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
472 /* Return the first available colour */
473 for (uint i = 0; i < COLOUR_END; i++) {
474 if (colours[i] != INVALID_COLOUR) return colours[i];
477 NOT_REACHED();
481 * Generate a random president name of a company.
482 * @param c Company that needs a new president name.
484 static void GeneratePresidentName(Company *c)
486 for (;;) {
487 restart:;
488 c->president_name_2 = Random();
489 c->president_name_1 = SPECSTR_PRESIDENT_NAME;
491 /* Reserve space for extra unicode character. We need to do this to be able
492 * to detect too long president name. */
493 char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
494 SetDParam(0, c->index);
495 GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
496 if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
498 for (const Company *cc : Company::Iterate()) {
499 if (c != cc) {
500 /* Reserve extra space so even overlength president names can be compared. */
501 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
502 SetDParam(0, cc->index);
503 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
504 if (strcmp(buffer2, buffer) == 0) goto restart;
507 return;
512 * Reset the livery schemes to the company's primary colour.
513 * This is used on loading games without livery information and on new company start up.
514 * @param c Company to reset.
516 void ResetCompanyLivery(Company *c)
518 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
519 c->livery[scheme].in_use = 0;
520 c->livery[scheme].colour1 = c->colour;
521 c->livery[scheme].colour2 = c->colour;
524 for (Group *g : Group::Iterate()) {
525 if (g->owner == c->index) {
526 g->livery.in_use = 0;
527 g->livery.colour1 = c->colour;
528 g->livery.colour2 = c->colour;
534 * Create a new company and sets all company variables default values
536 * @param is_ai is an AI company?
537 * @param company CompanyID to use for the new company
538 * @return the company struct
540 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
542 if (!Company::CanAllocateItem()) return nullptr;
544 /* we have to generate colour before this company is valid */
545 Colours colour = GenerateCompanyColour();
547 Company *c;
548 if (company == INVALID_COMPANY) {
549 c = new Company(STR_SV_UNNAMED, is_ai);
550 } else {
551 if (Company::IsValidID(company)) return nullptr;
552 c = new (company) Company(STR_SV_UNNAMED, is_ai);
555 c->colour = colour;
557 ResetCompanyLivery(c);
558 _company_colours[c->index] = (Colours)c->colour;
560 c->money = c->current_loan = (std::min<int64>(INITIAL_LOAN, _economy.max_loan) * _economy.inflation_prices >> 16) / 50000 * 50000;
562 std::fill(c->share_owners.begin(), c->share_owners.end(), INVALID_OWNER);
564 c->avail_railtypes = GetCompanyRailtypes(c->index);
565 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
566 c->inaugurated_year = _cur_year;
568 /* If starting a player company in singleplayer and a favorite company manager face is selected, choose it. Otherwise, use a random face.
569 * In a network game, we'll choose the favorite face later in CmdCompanyCtrl to sync it to all clients, but we choose it here for the first (host) company. */
570 if (_company_manager_face != 0 && !is_ai) {
571 c->face = _company_manager_face;
572 } else {
573 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false);
576 SetDefaultCompanySettings(c->index);
577 ClearEnginesHiddenFlagOfCompany(c->index);
579 GeneratePresidentName(c);
581 SetWindowDirty(WC_GRAPH_LEGEND, 0);
582 InvalidateWindowData(WC_CLIENT_LIST, 0);
583 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
584 BuildOwnerLegend();
585 InvalidateWindowData(WC_SMALLMAP, 0, 1);
587 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
589 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
590 Game::NewEvent(new ScriptEventCompanyNew(c->index));
592 return c;
595 /** Start the next competitor now. */
596 void StartupCompanies()
598 _next_competitor_start = 0;
601 /** Start a new competitor company if possible. */
602 static bool MaybeStartNewCompany()
604 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return false;
606 /* count number of competitors */
607 uint n = 0;
608 for (const Company *c : Company::Iterate()) {
609 if (c->is_ai) n++;
612 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
613 /* Send a command to all clients to start up a new AI.
614 * Works fine for Multiplayer and Singleplayer */
615 return Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID );
618 return false;
621 /** Initialize the pool of companies. */
622 void InitializeCompanies()
624 _cur_company_tick_index = 0;
628 * May company \a cbig buy company \a csmall?
629 * @param cbig Company buying \a csmall.
630 * @param csmall Company getting bought.
631 * @return Return \c true if it is allowed.
633 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
635 const Company *c1 = Company::Get(cbig);
636 const Company *c2 = Company::Get(csmall);
638 /* Do the combined vehicle counts stay within the limits? */
639 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
640 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
641 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
642 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
646 * Handle the bankruptcy take over of a company.
647 * Companies going bankrupt will ask the other companies in order of their
648 * performance rating, so better performing companies get the 'do you want to
649 * merge with Y' question earlier. The question will then stay till either the
650 * company has gone bankrupt or got merged with a company.
652 * @param c the company that is going bankrupt.
654 static void HandleBankruptcyTakeover(Company *c)
656 /* Amount of time out for each company to take over a company;
657 * Timeout is a quarter (3 months of 30 days) divided over the
658 * number of companies. The minimum number of days in a quarter
659 * is 90: 31 in January, 28 in February and 31 in March.
660 * Note that the company going bankrupt can't buy itself. */
661 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
663 assert(c->bankrupt_asked != 0);
665 /* We're currently asking some company to buy 'us' */
666 if (c->bankrupt_timeout != 0) {
667 c->bankrupt_timeout -= MAX_COMPANIES;
668 if (c->bankrupt_timeout > 0) return;
669 c->bankrupt_timeout = 0;
671 return;
674 /* Did we ask everyone for bankruptcy? If so, bail out. */
675 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
677 Company *best = nullptr;
678 int32 best_performance = -1;
680 /* Ask the company with the highest performance history first */
681 for (Company *c2 : Company::Iterate()) {
682 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
683 !HasBit(c->bankrupt_asked, c2->index) &&
684 best_performance < c2->old_economy[1].performance_history &&
685 MayCompanyTakeOver(c2->index, c->index)) {
686 best_performance = c2->old_economy[1].performance_history;
687 best = c2;
691 /* Asked all companies? */
692 if (best_performance == -1) {
693 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
694 return;
697 SetBit(c->bankrupt_asked, best->index);
699 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
700 if (best->is_ai) {
701 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
702 } else if (IsInteractiveCompany(best->index)) {
703 ShowBuyCompanyDialog(c->index);
707 /** Called every tick for updating some company info. */
708 void OnTick_Companies()
710 if (_game_mode == GM_EDITOR) return;
712 Company *c = Company::GetIfValid(_cur_company_tick_index);
713 if (c != nullptr) {
714 if (c->name_1 != 0) GenerateCompanyName(c);
715 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
718 if (_next_competitor_start == 0) {
719 /* AI::GetStartNextTime() can return 0. */
720 _next_competitor_start = std::max(1, AI::GetStartNextTime() * DAY_TICKS);
723 if (_game_mode != GM_MENU && AI::CanStartNew() && --_next_competitor_start == 0) {
724 /* Allow multiple AIs to possibly start in the same tick. */
725 do {
726 if (!MaybeStartNewCompany()) break;
728 /* In networking mode, we can only send a command to start but it
729 * didn't execute yet, so we cannot loop. */
730 if (_networking) break;
731 } while (AI::GetStartNextTime() == 0);
734 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
738 * A year has passed, update the economic data of all companies, and perhaps show the
739 * financial overview window of the local company.
741 void CompaniesYearlyLoop()
743 /* Copy statistics */
744 for (Company *c : Company::Iterate()) {
745 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
746 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
747 SetWindowDirty(WC_FINANCES, c->index);
750 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
751 ShowCompanyFinances(_local_company);
752 Company *c = Company::Get(_local_company);
753 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
754 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
755 } else {
756 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
762 * Fill the CompanyNewsInformation struct with the required data.
763 * @param c the current company.
764 * @param other the other company (use \c nullptr if not relevant).
766 CompanyNewsInformation::CompanyNewsInformation(const Company *c, const Company *other)
768 SetDParam(0, c->index);
769 this->company_name = GetString(STR_COMPANY_NAME);
771 if (other != nullptr) {
772 SetDParam(0, other->index);
773 this->other_company_name = GetString(STR_COMPANY_NAME);
774 c = other;
777 SetDParam(0, c->index);
778 this->president_name = GetString(STR_PRESIDENT_NAME_MANAGER);
780 this->colour = c->colour;
781 this->face = c->face;
786 * Called whenever company related information changes in order to notify admins.
787 * @param company The company data changed of.
789 void CompanyAdminUpdate(const Company *company)
791 if (_network_server) NetworkAdminCompanyUpdate(company);
795 * Called whenever a company is removed in order to notify admins.
796 * @param company_id The company that was removed.
797 * @param reason The reason the company was removed.
799 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
801 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
805 * Control the companies: add, delete, etc.
806 * @param flags operation to perform
807 * @param cca action to perform
808 * @param company_id company to perform the action on
809 * @param client_id ClientID
810 * @return the cost of this operation or an error
812 CommandCost CmdCompanyCtrl(DoCommandFlag flags, CompanyCtrlAction cca, CompanyID company_id, CompanyRemoveReason reason, ClientID client_id)
814 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
816 switch (cca) {
817 case CCA_NEW: { // Create a new company
818 /* This command is only executed in a multiplayer game */
819 if (!_networking) return CMD_ERROR;
821 /* Has the network client a correct ClientIndex? */
822 if (!(flags & DC_EXEC)) return CommandCost();
824 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
826 /* Delete multiplayer progress bar */
827 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
829 Company *c = DoStartupNewCompany(false);
831 /* A new company could not be created, revert to being a spectator */
832 if (c == nullptr) {
833 /* We check for "ci != nullptr" as a client could have left by
834 * the time we execute this command. */
835 if (_network_server && ci != nullptr) {
836 ci->client_playas = COMPANY_SPECTATOR;
837 NetworkUpdateClientInfo(ci->client_id);
839 break;
842 /* This is the client (or non-dedicated server) who wants a new company */
843 if (client_id == _network_own_client_id) {
844 assert(_local_company == COMPANY_SPECTATOR);
845 SetLocalCompany(c->index);
846 if (!_settings_client.network.default_company_pass.empty()) {
847 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
850 /* In network games, we need to try setting the company manager face here to sync it to all clients.
851 * If a favorite company manager face is selected, choose it. Otherwise, use a random face. */
852 if (_company_manager_face != 0) Command<CMD_SET_COMPANY_MANAGER_FACE>::SendNet(STR_NULL, c->index, _company_manager_face);
854 /* Now that we have a new company, broadcast our company settings to
855 * all clients so everything is in sync */
856 SyncCompanySettings();
858 MarkWholeScreenDirty();
861 NetworkServerNewCompany(c, ci);
862 break;
865 case CCA_NEW_AI: { // Make a new AI company
866 if (company_id != INVALID_COMPANY && company_id >= MAX_COMPANIES) return CMD_ERROR;
868 /* For network games, company deletion is delayed. */
869 if (!_networking && company_id != INVALID_COMPANY && Company::IsValidID(company_id)) return CMD_ERROR;
871 if (!(flags & DC_EXEC)) return CommandCost();
873 /* For network game, just assume deletion happened. */
874 assert(company_id == INVALID_COMPANY || !Company::IsValidID(company_id));
876 Company *c = DoStartupNewCompany(true, company_id);
877 if (c != nullptr) NetworkServerNewCompany(c, nullptr);
878 break;
881 case CCA_DELETE: { // Delete a company
882 if (reason >= CRR_END) return CMD_ERROR;
884 /* We can't delete the last existing company in singleplayer mode. */
885 if (!_networking && Company::GetNumItems() == 1) return CMD_ERROR;
887 Company *c = Company::GetIfValid(company_id);
888 if (c == nullptr) return CMD_ERROR;
890 if (!(flags & DC_EXEC)) return CommandCost();
892 /* Delete any open window of the company */
893 CloseCompanyWindows(c->index);
894 CompanyNewsInformation *cni = new CompanyNewsInformation(c);
896 /* Show the bankrupt news */
897 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
898 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
899 SetDParamStr(2, cni->company_name);
900 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
902 /* Remove the company */
903 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
904 if (c->is_ai) AI::Stop(c->index);
906 CompanyID c_index = c->index;
907 delete c;
908 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
909 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
910 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
912 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
913 InvalidateWindowData(WC_CLIENT_LIST, 0);
915 break;
918 default: return CMD_ERROR;
921 InvalidateWindowClassesData(WC_GAME_OPTIONS);
922 InvalidateWindowClassesData(WC_AI_SETTINGS);
923 InvalidateWindowClassesData(WC_AI_LIST);
925 return CommandCost();
929 * Change the company manager's face.
930 * @param flags operation to perform
931 * @param cmf face bitmasked
932 * @return the cost of this operation or an error
934 CommandCost CmdSetCompanyManagerFace(DoCommandFlag flags, CompanyManagerFace cmf)
936 if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
938 if (flags & DC_EXEC) {
939 Company::Get(_current_company)->face = cmf;
940 MarkWholeScreenDirty();
942 return CommandCost();
946 * Change the company's company-colour
947 * @param flags operation to perform
948 * @param scheme scheme to set
949 * @param primary set first/second colour
950 * @param colour new colour for vehicles, property, etc.
951 * @return the cost of this operation or an error
953 CommandCost CmdSetCompanyColour(DoCommandFlag flags, LiveryScheme scheme, bool primary, Colours colour)
955 if (scheme >= LS_END || (colour >= COLOUR_END && colour != INVALID_COLOUR)) return CMD_ERROR;
957 /* Default scheme can't be reset to invalid. */
958 if (scheme == LS_DEFAULT && colour == INVALID_COLOUR) return CMD_ERROR;
960 Company *c = Company::Get(_current_company);
962 /* Ensure no two companies have the same primary colour */
963 if (scheme == LS_DEFAULT && primary) {
964 for (const Company *cc : Company::Iterate()) {
965 if (cc != c && cc->colour == colour) return CMD_ERROR;
969 if (flags & DC_EXEC) {
970 if (primary) {
971 if (scheme != LS_DEFAULT) SB(c->livery[scheme].in_use, 0, 1, colour != INVALID_COLOUR);
972 if (colour == INVALID_COLOUR) colour = (Colours)c->livery[LS_DEFAULT].colour1;
973 c->livery[scheme].colour1 = colour;
975 /* If setting the first colour of the default scheme, adjust the
976 * original and cached company colours too. */
977 if (scheme == LS_DEFAULT) {
978 for (int i = 1; i < LS_END; i++) {
979 if (!HasBit(c->livery[i].in_use, 0)) c->livery[i].colour1 = colour;
981 _company_colours[_current_company] = colour;
982 c->colour = colour;
983 CompanyAdminUpdate(c);
985 } else {
986 if (scheme != LS_DEFAULT) SB(c->livery[scheme].in_use, 1, 1, colour != INVALID_COLOUR);
987 if (colour == INVALID_COLOUR) colour = (Colours)c->livery[LS_DEFAULT].colour2;
988 c->livery[scheme].colour2 = colour;
990 if (scheme == LS_DEFAULT) {
991 for (int i = 1; i < LS_END; i++) {
992 if (!HasBit(c->livery[i].in_use, 1)) c->livery[i].colour2 = colour;
997 if (c->livery[scheme].in_use != 0) {
998 /* If enabling a scheme, set the default scheme to be in use too */
999 c->livery[LS_DEFAULT].in_use = 1;
1000 } else {
1001 /* Else loop through all schemes to see if any are left enabled.
1002 * If not, disable the default scheme too. */
1003 c->livery[LS_DEFAULT].in_use = 0;
1004 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1005 if (c->livery[scheme].in_use != 0) {
1006 c->livery[LS_DEFAULT].in_use = 1;
1007 break;
1012 ResetVehicleColourMap();
1013 MarkWholeScreenDirty();
1015 /* All graph related to companies use the company colour. */
1016 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1017 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1018 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1019 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1020 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1021 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1022 /* The smallmap owner view also stores the company colours. */
1023 BuildOwnerLegend();
1024 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1026 /* Company colour data is indirectly cached. */
1027 for (Vehicle *v : Vehicle::Iterate()) {
1028 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1031 extern void UpdateObjectColours(const Company *c);
1032 UpdateObjectColours(c);
1034 return CommandCost();
1038 * Is the given name in use as name of a company?
1039 * @param name Name to search.
1040 * @return \c true if the name us unique (that is, not in use), else \c false.
1042 static bool IsUniqueCompanyName(const std::string &name)
1044 for (const Company *c : Company::Iterate()) {
1045 if (!c->name.empty() && c->name == name) return false;
1048 return true;
1052 * Change the name of the company.
1053 * @param flags operation to perform
1054 * @param text the new name or an empty string when resetting to the default
1055 * @return the cost of this operation or an error
1057 CommandCost CmdRenameCompany(DoCommandFlag flags, const std::string &text)
1059 bool reset = text.empty();
1061 if (!reset) {
1062 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
1063 if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1066 if (flags & DC_EXEC) {
1067 Company *c = Company::Get(_current_company);
1068 if (reset) {
1069 c->name.clear();
1070 } else {
1071 c->name = text;
1073 MarkWholeScreenDirty();
1074 CompanyAdminUpdate(c);
1077 return CommandCost();
1081 * Is the given name in use as president name of a company?
1082 * @param name Name to search.
1083 * @return \c true if the name us unique (that is, not in use), else \c false.
1085 static bool IsUniquePresidentName(const std::string &name)
1087 for (const Company *c : Company::Iterate()) {
1088 if (!c->president_name.empty() && c->president_name == name) return false;
1091 return true;
1095 * Change the name of the president.
1096 * @param flags operation to perform
1097 * @param text the new name or an empty string when resetting to the default
1098 * @return the cost of this operation or an error
1100 CommandCost CmdRenamePresident(DoCommandFlag flags, const std::string &text)
1102 bool reset = text.empty();
1104 if (!reset) {
1105 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
1106 if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1109 if (flags & DC_EXEC) {
1110 Company *c = Company::Get(_current_company);
1112 if (reset) {
1113 c->president_name.clear();
1114 } else {
1115 c->president_name = text;
1117 if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) {
1118 Command<CMD_RENAME_COMPANY>::Do(DC_EXEC, text + " Transport");
1122 MarkWholeScreenDirty();
1123 CompanyAdminUpdate(c);
1126 return CommandCost();
1130 * Get the service interval for the given company and vehicle type.
1131 * @param c The company, or nullptr for client-default settings.
1132 * @param type The vehicle type to get the interval for.
1133 * @return The service interval.
1135 int CompanyServiceInterval(const Company *c, VehicleType type)
1137 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1138 switch (type) {
1139 default: NOT_REACHED();
1140 case VEH_TRAIN: return vds->servint_trains;
1141 case VEH_ROAD: return vds->servint_roadveh;
1142 case VEH_AIRCRAFT: return vds->servint_aircraft;
1143 case VEH_SHIP: return vds->servint_ships;
1148 * Get total sum of all owned road bits.
1149 * @return Combined total road road bits.
1151 uint32 CompanyInfrastructure::GetRoadTotal() const
1153 uint32 total = 0;
1154 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1155 if (RoadTypeIsRoad(rt)) total += this->road[rt];
1157 return total;
1161 * Get total sum of all owned tram bits.
1162 * @return Combined total of tram road bits.
1164 uint32 CompanyInfrastructure::GetTramTotal() const
1166 uint32 total = 0;
1167 for (RoadType rt = ROADTYPE_BEGIN; rt != ROADTYPE_END; rt++) {
1168 if (RoadTypeIsTram(rt)) total += this->road[rt];
1170 return total;
1174 * Transfer funds (money) from one company to another.
1175 * To prevent abuse in multiplayer games you can only send money to other
1176 * companies if you have paid off your loan (either explicitly, or implicitly
1177 * given the fact that you have more money than loan).
1178 * @param flags operation to perform
1179 * @param money the amount of money to transfer; max 20.000.000
1180 * @param dest_company the company to transfer the money to
1181 * @return the cost of this operation or an error
1183 CommandCost CmdGiveMoney(DoCommandFlag flags, uint32 money, CompanyID dest_company)
1185 if (!_settings_game.economy.give_money) return CMD_ERROR;
1187 const Company *c = Company::Get(_current_company);
1188 CommandCost amount(EXPENSES_OTHER, std::min<Money>(money, 20000000LL));
1190 /* You can only transfer funds that is in excess of your loan */
1191 if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() < 0) return_cmd_error(STR_ERROR_INSUFFICIENT_FUNDS);
1192 if (!Company::IsValidID(dest_company)) return CMD_ERROR;
1194 if (flags & DC_EXEC) {
1195 /* Add money to company */
1196 Backup<CompanyID> cur_company(_current_company, dest_company, FILE_LINE);
1197 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, -amount.GetCost()));
1198 cur_company.Restore();
1200 if (_networking) {
1201 SetDParam(0, dest_company);
1202 std::string dest_company_name = GetString(STR_COMPANY_NAME);
1204 SetDParam(0, _current_company);
1205 std::string from_company_name = GetString(STR_COMPANY_NAME);
1207 NetworkTextMessage(NETWORK_ACTION_GIVE_MONEY, GetDrawStringCompanyColour(_current_company), false, from_company_name, dest_company_name, amount.GetCost());
1211 /* Subtract money from local-company */
1212 return amount;
1216 * Get the index of the first available company. It attempts,
1217 * from first to last, and as soon as the attempt succeeds,
1218 * to get the index of the company:
1219 * 1st - get the first existing human company.
1220 * 2nd - get the first non-existing company.
1221 * 3rd - get COMPANY_FIRST.
1222 * @return the index of the first available company.
1224 CompanyID GetFirstPlayableCompanyID()
1226 for (Company *c : Company::Iterate()) {
1227 if (Company::IsHumanID(c->index)) {
1228 return c->index;
1232 if (Company::CanAllocateItem()) {
1233 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1234 if (!Company::IsValidID(c)) {
1235 return c;
1240 return COMPANY_FIRST;