Update readme and changelog for v1.26.0
[openttd-joker.git] / src / company_cmd.cpp
blob8f2154d9b7254ceab564a2f21dcf87cf31b5cf92
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 company_cmd.cpp Handling of companies. */
12 #include "stdafx.h"
13 #include "company_base.h"
14 #include "company_func.h"
15 #include "company_gui.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "cmd_helper.h"
19 #include "command_func.h"
20 #include "network/network.h"
21 #include "network/network_func.h"
22 #include "network/network_base.h"
23 #include "network/network_admin.h"
24 #include "ai/ai.hpp"
25 #include "company_manager_face.h"
26 #include "window_func.h"
27 #include "strings_func.h"
28 #include "date_func.h"
29 #include "sound_func.h"
30 #include "rail.h"
31 #include "core/pool_func.hpp"
32 #include "settings_func.h"
33 #include "vehicle_base.h"
34 #include "vehicle_func.h"
35 #include "smallmap_gui.h"
36 #include "game/game.hpp"
37 #include "goal_base.h"
38 #include "story_base.h"
39 #include "zoning.h"
41 #include "table/strings.h"
43 #include "safeguards.h"
45 void ClearEnginesHiddenFlagOfCompany(CompanyID cid);
47 CompanyByte _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
48 CompanyByte _current_company; ///< Company currently doing an action.
49 Colours _company_colours[MAX_COMPANIES]; ///< NOSAVE: can be determined from company structs.
50 CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
51 uint _next_competitor_start; ///< the number of ticks before the next AI is started
52 uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
54 CompanyPool _company_pool("Company"); ///< Pool of companies.
55 INSTANTIATE_POOL_METHODS(Company)
57 /**
58 * Constructor.
59 * @param name_1 Name of the company.
60 * @param is_ai A computer program is running for this company.
62 Company::Company(uint16 name_1, bool is_ai)
64 this->name_1 = name_1;
65 this->location_of_HQ = INVALID_TILE;
66 this->is_ai = is_ai;
67 this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
68 this->clear_limit = _settings_game.construction.clear_frame_burst << 16;
69 this->tree_limit = _settings_game.construction.tree_frame_burst << 16;
71 for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
72 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
75 /** Destructor. */
76 Company::~Company()
78 if (CleaningPool()) return;
80 DeleteCompanyWindows(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 #ifdef ENABLE_NETWORK
109 /* Delete the chat window, if you were team chatting. */
110 InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
111 #endif
113 assert(IsLocalCompany());
115 _current_company = _local_company = new_company;
117 /* Delete any construction windows... */
118 DeleteConstructionWindows();
120 /* ... and redraw the whole screen. */
121 MarkWholeScreenDirty();
122 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
123 ClearZoningCaches();
127 * Get the colour for DrawString-subroutines which matches the colour of the company.
128 * @param company Company to get the colour of.
129 * @return Colour of \a company.
131 TextColour GetDrawStringCompanyColour(CompanyID company)
133 if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
134 return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
138 * Draw the icon of a company.
139 * @param c Company that needs its icon drawn.
140 * @param x Horizontal coordinate of the icon.
141 * @param y Vertical coordinate of the icon.
143 void DrawCompanyIcon(CompanyID c, int x, int y)
145 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
149 * Checks whether a company manager's face is a valid encoding.
150 * Unused bits are not enforced to be 0.
151 * @param cmf the fact to check
152 * @return true if and only if the face is valid
154 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
156 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
158 GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
159 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
160 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
161 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
163 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
164 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
165 switch (cmfv) {
166 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
167 case CMFV_LIPS:
168 case CMFV_NOSE: if (has_moustache) continue; break;
169 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
170 case CMFV_GLASSES: if (!has_glasses) continue; break;
171 default: break;
173 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
176 return true;
180 * Refresh all windows owned by a company.
181 * @param company Company that changed, and needs its windows refreshed.
183 void InvalidateCompanyWindows(const Company *company)
185 CompanyID cid = company->index;
187 if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
188 SetWindowDirty(WC_FINANCES, cid);
192 * Verify whether the company can pay the bill.
193 * @param cost [inout] Money to pay, is changed to an error if the company does not have enough money.
194 * @return Function returns \c true if the company has enough money, else it returns \c false.
196 bool CheckCompanyHasMoney(CommandCost &cost)
198 if (cost.GetCost() > 0) {
199 const Company *c = Company::GetIfValid(_current_company);
200 if (c != nullptr && cost.GetCost() > c->money) {
201 SetDParam(0, cost.GetCost());
202 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
203 return false;
206 return true;
210 * Deduct costs of a command from the money of a company.
211 * @param c Company to pay the bill.
212 * @param cost Money to pay.
214 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
216 if (cost.GetCost() == 0) return;
217 assert(cost.GetExpensesType() != INVALID_EXPENSES);
219 c->money -= cost.GetCost();
220 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
222 if (HasBit(1 << EXPENSES_TRAIN_INC |
223 1 << EXPENSES_ROADVEH_INC |
224 1 << EXPENSES_AIRCRAFT_INC |
225 1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
226 c->cur_economy.income -= cost.GetCost();
227 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
228 1 << EXPENSES_ROADVEH_RUN |
229 1 << EXPENSES_AIRCRAFT_RUN |
230 1 << EXPENSES_SHIP_RUN |
231 1 << EXPENSES_PROPERTY |
232 1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
233 c->cur_economy.expenses -= cost.GetCost();
236 InvalidateCompanyWindows(c);
240 * Subtract money from the #_current_company, if the company is valid.
241 * @param cost Money to pay.
243 void SubtractMoneyFromCompany(CommandCost cost)
245 Company *c = Company::GetIfValid(_current_company);
246 if (c != nullptr) SubtractMoneyFromAnyCompany(c, cost);
250 * Subtract money from a company, including the money fraction.
251 * @param company Company paying the bill.
252 * @param cst Cost of a command.
254 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
256 Company *c = Company::Get(company);
257 byte m = c->money_fraction;
258 Money cost = cst.GetCost();
260 c->money_fraction = m - (byte)cost;
261 cost >>= 8;
262 if (c->money_fraction > m) cost++;
263 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
266 /** Update the landscaping limits per company. */
267 void UpdateLandscapingLimits()
269 Company *c;
270 FOR_ALL_COMPANIES(c) {
271 c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
272 c->clear_limit = min(c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint32)_settings_game.construction.clear_frame_burst << 16);
273 c->tree_limit = min(c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint32)_settings_game.construction.tree_frame_burst << 16);
278 * Set the right DParams to get the name of an owner.
279 * @param owner the owner to get the name of.
280 * @param tile optional tile to get the right town.
281 * @pre if tile == 0, then owner can't be OWNER_TOWN.
283 void GetNameOfOwner(Owner owner, TileIndex tile)
285 SetDParam(2, owner);
287 if (owner != OWNER_TOWN) {
288 if (!Company::IsValidID(owner)) {
289 SetDParam(0, STR_COMPANY_SOMEONE);
290 } else {
291 SetDParam(0, STR_COMPANY_NAME);
292 SetDParam(1, owner);
294 } else {
295 assert(tile != 0);
296 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
298 SetDParam(0, STR_TOWN_NAME);
299 SetDParam(1, t->index);
305 * Check whether the current owner owns something.
306 * If that isn't the case an appropriate error will be given.
307 * @param owner the owner of the thing to check.
308 * @param tile optional tile to get the right town.
309 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
310 * @return A succeeded command iff it's owned by the current company, else a failed command.
312 CommandCost CheckOwnership(Owner owner, TileIndex tile)
314 assert(owner < OWNER_END);
315 assert(owner != OWNER_TOWN || tile != 0);
317 if (owner == _current_company) return CommandCost();
319 GetNameOfOwner(owner, tile);
320 return CommandError(STR_ERROR_OWNED_BY);
324 * Check whether the current owner owns the stuff on
325 * the given tile. If that isn't the case an
326 * appropriate error will be given.
327 * @param tile the tile to check.
328 * @return A succeeded command iff it's owned by the current company, else a failed command.
330 CommandCost CheckTileOwnership(TileIndex tile)
332 Owner owner = GetTileOwner(tile);
334 assert(owner < OWNER_END);
336 if (owner == _current_company) return CommandCost();
338 /* no need to get the name of the owner unless we're the local company (saves some time) */
339 if (IsLocalCompany()) GetNameOfOwner(owner, tile);
340 return CommandError(STR_ERROR_OWNED_BY);
344 * Generate the name of a company from the last build coordinate.
345 * @param c Company to give a name.
347 static void GenerateCompanyName(Company *c)
349 /* Reserve space for extra unicode character. We need to do this to be able
350 * to detect too long company name. */
351 char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
353 if (c->name_1 != STR_SV_UNNAMED) return;
354 if (c->last_build_coordinate == 0) return;
356 Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
358 StringID str;
359 uint32 strp;
360 if (t->name == nullptr && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
361 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
362 strp = t->townnameparts;
364 verify_name:;
365 /* No companies must have this name already */
366 Company *cc;
367 FOR_ALL_COMPANIES(cc) {
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 = MallocT<CompanyNewsInformation>(1);
382 cni->FillData(c);
383 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
384 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
385 SetDParamStr(2, cni->company_name);
386 SetDParam(3, t->index);
387 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
389 return;
391 bad_town_name:;
393 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
394 str = SPECSTR_ANDCO_NAME;
395 strp = c->president_name_2;
396 goto set_name;
397 } else {
398 str = SPECSTR_ANDCO_NAME;
399 strp = Random();
400 goto verify_name;
404 /** Sorting weights for the company colours. */
405 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
406 /** Similar colours, so we can try to prevent same coloured companies. */
407 static const Colours _similar_colour[COLOUR_END][2] = {
408 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
409 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
410 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
411 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
412 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
413 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
414 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
415 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
416 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
417 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
418 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
419 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
420 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
421 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
422 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
423 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
427 * Generate a company colour.
428 * @return Generated company colour.
430 static Colours GenerateCompanyColour()
432 Colours colours[COLOUR_END];
434 /* Initialize array */
435 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
437 /* And randomize it */
438 for (uint i = 0; i < 100; i++) {
439 uint r = Random();
440 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
443 /* Bubble sort it according to the values in table 1 */
444 for (uint i = 0; i < COLOUR_END; i++) {
445 for (uint j = 1; j < COLOUR_END; j++) {
446 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
447 Swap(colours[j - 1], colours[j]);
452 /* Move the colours that look similar to each company's colour to the side */
453 Company *c;
454 FOR_ALL_COMPANIES(c) {
455 Colours pcolour = (Colours)c->colour;
457 for (uint i = 0; i < COLOUR_END; i++) {
458 if (colours[i] == pcolour) {
459 colours[i] = INVALID_COLOUR;
460 break;
464 for (uint j = 0; j < 2; j++) {
465 Colours similar = _similar_colour[pcolour][j];
466 if (similar == INVALID_COLOUR) break;
468 for (uint i = 1; i < COLOUR_END; i++) {
469 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
474 /* Return the first available colour */
475 for (uint i = 0; i < COLOUR_END; i++) {
476 if (colours[i] != INVALID_COLOUR) return colours[i];
479 NOT_REACHED();
483 * Generate a random president name of a company.
484 * @param c Company that needs a new president name.
486 static void GeneratePresidentName(Company *c)
488 for (;;) {
489 restart:;
490 c->president_name_2 = Random();
491 c->president_name_1 = SPECSTR_PRESIDENT_NAME;
493 /* Reserve space for extra unicode character. We need to do this to be able
494 * to detect too long president name. */
495 char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
496 SetDParam(0, c->index);
497 GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
498 if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
500 Company *cc;
501 FOR_ALL_COMPANIES(cc) {
502 if (c != cc) {
503 /* Reserve extra space so even overlength president names can be compared. */
504 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
505 SetDParam(0, cc->index);
506 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
507 if (strcmp(buffer2, buffer) == 0) goto restart;
510 return;
515 * Reset the livery schemes to the company's primary colour.
516 * This is used on loading games without livery information and on new company start up.
517 * @param c Company to reset.
519 void ResetCompanyLivery(Company *c)
521 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
522 c->livery[scheme].in_use = false;
523 c->livery[scheme].colour1 = c->colour;
524 c->livery[scheme].colour2 = c->colour;
529 * Create a new company and sets all company variables default values
531 * @param is_ai is an AI company?
532 * @param company CompanyID to use for the new company
533 * @return the company struct
535 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
537 if (!Company::CanAllocateItem()) return nullptr;
539 /* we have to generate colour before this company is valid */
540 Colours colour = GenerateCompanyColour();
542 Company *c;
543 if (company == INVALID_COMPANY) {
544 c = new Company(STR_SV_UNNAMED, is_ai);
545 } else {
546 if (Company::IsValidID(company)) return nullptr;
547 c = new (company) Company(STR_SV_UNNAMED, is_ai);
550 c->colour = colour;
552 ResetCompanyLivery(c);
553 _company_colours[c->index] = (Colours)c->colour;
555 c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
557 c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
559 c->avail_railtypes = GetCompanyRailtypes(c->index);
560 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
561 c->inaugurated_year = _cur_year;
562 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false); // create a random company manager face
564 SetDefaultCompanySettings(c->index);
565 ClearEnginesHiddenFlagOfCompany(c->index);
567 GeneratePresidentName(c);
569 SetWindowDirty(WC_GRAPH_LEGEND, 0);
570 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
571 SetWindowDirty(WC_CLIENT_LIST, 0);
572 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
573 BuildOwnerLegend();
574 InvalidateWindowData(WC_SMALLMAP, 0, 1);
576 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
578 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
579 Game::NewEvent(new ScriptEventCompanyNew(c->index));
581 if (!is_ai) UpdateAllTownVirtCoords();
583 return c;
586 /** Start the next competitor now. */
587 void StartupCompanies()
589 _next_competitor_start = 0;
592 /** Start a new competitor company if possible. */
593 static void MaybeStartNewCompany()
595 #ifdef ENABLE_NETWORK
596 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
597 #endif /* ENABLE_NETWORK */
599 Company *c;
601 /* count number of competitors */
602 uint n = 0;
603 FOR_ALL_COMPANIES(c) {
604 if (c->is_ai) n++;
607 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
608 /* Send a command to all clients to start up a new AI.
609 * Works fine for Multiplayer and Singleplayer */
610 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
614 /** Initialize the pool of companies. */
615 void InitializeCompanies()
617 _cur_company_tick_index = 0;
621 * May company \a cbig buy company \a csmall?
622 * @param cbig Company buying \a csmall.
623 * @param csmall Company getting bought.
624 * @return Return \c true if it is allowed.
626 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
628 const Company *c1 = Company::Get(cbig);
629 const Company *c2 = Company::Get(csmall);
631 /* Do the combined vehicle counts stay within the limits? */
632 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
633 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
634 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
635 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
639 * Handle the bankruptcy take over of a company.
640 * Companies going bankrupt will ask the other companies in order of their
641 * performance rating, so better performing companies get the 'do you want to
642 * merge with Y' question earlier. The question will then stay till either the
643 * company has gone bankrupt or got merged with a company.
645 * @param c the company that is going bankrupt.
647 static void HandleBankruptcyTakeover(Company *c)
649 /* Amount of time out for each company to take over a company;
650 * Timeout is a quarter (3 months of 30 days) divided over the
651 * number of companies. The minimum number of days in a quarter
652 * is 90: 31 in January, 28 in February and 31 in March.
653 * Note that the company going bankrupt can't buy itself. */
654 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
656 assert(c->bankrupt_asked != 0);
658 /* We're currently asking some company to buy 'us' */
659 if (c->bankrupt_timeout != 0) {
660 c->bankrupt_timeout -= MAX_COMPANIES;
661 if (c->bankrupt_timeout > 0) return;
662 c->bankrupt_timeout = 0;
664 return;
667 /* Did we ask everyone for bankruptcy? If so, bail out. */
668 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
670 Company *c2, *best = nullptr;
671 int32 best_performance = -1;
673 /* Ask the company with the highest performance history first */
674 FOR_ALL_COMPANIES(c2) {
675 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
676 !HasBit(c->bankrupt_asked, c2->index) &&
677 best_performance < c2->old_economy[1].performance_history &&
678 MayCompanyTakeOver(c2->index, c->index)) {
679 best_performance = c2->old_economy[1].performance_history;
680 best = c2;
684 /* Asked all companies? */
685 if (best_performance == -1) {
686 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
687 return;
690 SetBit(c->bankrupt_asked, best->index);
692 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
693 if (best->is_ai) {
694 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
695 } else if (IsInteractiveCompany(best->index)) {
696 ShowBuyCompanyDialog(c->index);
700 /** Called every tick for updating some company info. */
701 void OnTick_Companies()
703 if (_game_mode == GM_EDITOR) return;
705 Company *c = Company::GetIfValid(_cur_company_tick_index);
706 if (c != nullptr) {
707 if (c->name_1 != 0) GenerateCompanyName(c);
708 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
711 if (_next_competitor_start == 0) {
712 _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
715 if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
716 MaybeStartNewCompany();
719 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
723 * A year has passed, update the economic data of all companies, and perhaps show the
724 * financial overview window of the local company.
726 void CompaniesYearlyLoop()
728 Company *c;
730 /* Copy statistics */
731 FOR_ALL_COMPANIES(c) {
732 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
733 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
734 SetWindowDirty(WC_FINANCES, c->index);
737 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
738 ShowCompanyFinances(_local_company);
739 c = Company::Get(_local_company);
740 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
741 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
742 } else {
743 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
749 * Fill the CompanyNewsInformation struct with the required data.
750 * @param c the current company.
751 * @param other the other company (use \c nullptr if not relevant).
753 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
755 SetDParam(0, c->index);
756 GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
758 if (other == nullptr) {
759 *this->other_company_name = '\0';
760 } else {
761 SetDParam(0, other->index);
762 GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
763 c = other;
766 SetDParam(0, c->index);
767 GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
769 this->colour = c->colour;
770 this->face = c->face;
775 * Called whenever company related information changes in order to notify admins.
776 * @param company The company data changed of.
778 void CompanyAdminUpdate(const Company *company)
780 #ifdef ENABLE_NETWORK
781 if (_network_server) NetworkAdminCompanyUpdate(company);
782 #endif /* ENABLE_NETWORK */
786 * Called whenever a company is removed in order to notify admins.
787 * @param company_id The company that was removed.
788 * @param reason The reason the company was removed.
790 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
792 #ifdef ENABLE_NETWORK
793 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
794 #endif /* ENABLE_NETWORK */
798 * Control the companies: add, delete, etc.
799 * @param tile unused
800 * @param flags operation to perform
801 * @param p1 various functionality
802 * - bits 0..15:
803 * = 0 - create a new company
804 * = 1 - create a new AI company
805 * = 2 - delete a company
806 * - bits 16..24: CompanyID
807 * @param p2 ClientID
808 * @param text unused
809 * @return the cost of this operation or an error
811 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
813 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
814 CompanyID company_id = (CompanyID)GB(p1, 16, 8);
815 #ifdef ENABLE_NETWORK
816 ClientID client_id = (ClientID)p2;
817 #endif /* ENABLE_NETWORK */
819 switch (GB(p1, 0, 16)) {
820 case 0: { // Create a new company
821 /* This command is only executed in a multiplayer game */
822 if (!_networking) return CommandError();
824 #ifdef ENABLE_NETWORK
825 /* Has the network client a correct ClientIndex? */
826 if (!(flags & DC_EXEC)) return CommandCost();
827 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
828 #ifndef DEBUG_DUMP_COMMANDS
829 /* When replaying the client ID is not a valid client; there
830 * are actually no clients at all. However, the company has to
831 * be created, otherwise we cannot rerun the game properly.
832 * So only allow a nullptr client info in that case. */
833 if (ci == nullptr) return CommandCost();
834 #endif /* NOT DEBUG_DUMP_COMMANDS */
836 /* Delete multiplayer progress bar */
837 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
839 Company *c = DoStartupNewCompany(false);
841 /* A new company could not be created, revert to being a spectator */
842 if (c == nullptr) {
843 if (_network_server) {
844 ci->client_playas = COMPANY_SPECTATOR;
845 NetworkUpdateClientInfo(ci->client_id);
847 break;
850 /* This is the client (or non-dedicated server) who wants a new company */
851 if (client_id == _network_own_client_id) {
852 assert(_local_company == COMPANY_SPECTATOR);
853 SetLocalCompany(c->index);
854 if (!StrEmpty(_settings_client.network.default_company_pass)) {
855 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
858 /* Now that we have a new company, broadcast our company settings to
859 * all clients so everything is in sync */
860 SyncCompanySettings();
862 MarkWholeScreenDirty();
865 NetworkServerNewCompany(c, ci);
866 #endif /* ENABLE_NETWORK */
867 break;
870 case 1: { // Make a new AI company
871 if (!(flags & DC_EXEC)) return CommandCost();
873 if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CommandError();
874 Company *c = DoStartupNewCompany(true, company_id);
875 #ifdef ENABLE_NETWORK
876 if (c != nullptr) NetworkServerNewCompany(c, nullptr);
877 #endif /* ENABLE_NETWORK */
878 break;
881 case 2: { // Delete a company
882 CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
883 if (reason >= CRR_END) return CommandError();
885 Company *c = Company::GetIfValid(company_id);
886 if (c == nullptr) return CommandError();
888 if (!(flags & DC_EXEC)) return CommandCost();
890 /* Delete any open window of the company */
891 DeleteCompanyWindows(c->index);
892 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
893 cni->FillData(c);
895 /* Show the bankrupt news */
896 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
897 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
898 SetDParamStr(2, cni->company_name);
899 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
901 /* Remove the company */
902 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
903 if (c->is_ai) AI::Stop(c->index);
905 CompanyID c_index = c->index;
906 delete c;
907 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
908 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
909 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
911 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
912 break;
915 default: return CommandError();
918 InvalidateWindowClassesData(WC_GAME_OPTIONS);
919 InvalidateWindowClassesData(WC_AI_SETTINGS);
920 InvalidateWindowClassesData(WC_AI_LIST);
922 return CommandCost();
926 * Change the company manager's face.
927 * @param tile unused
928 * @param flags operation to perform
929 * @param p1 unused
930 * @param p2 face bitmasked
931 * @param text unused
932 * @return the cost of this operation or an error
934 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
936 CompanyManagerFace cmf = (CompanyManagerFace)p2;
938 if (!IsValidCompanyManagerFace(cmf)) return CommandError();
940 if (flags & DC_EXEC) {
941 Company::Get(_current_company)->face = cmf;
942 MarkWholeScreenDirty();
944 return CommandCost();
948 * Change the company's company-colour
949 * @param tile unused
950 * @param flags operation to perform
951 * @param p1 bitstuffed:
952 * p1 bits 0-7 scheme to set
953 * p1 bits 8-9 set in use state or first/second colour
954 * @param p2 new colour for vehicles, property, etc.
955 * @param text unused
956 * @return the cost of this operation or an error
958 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
960 Colours colour = Extract<Colours, 0, 4>(p2);
961 LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
962 byte state = GB(p1, 8, 2);
964 if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CommandError();
966 Company *c = Company::Get(_current_company);
968 /* Ensure no two companies have the same primary colour */
969 if (scheme == LS_DEFAULT && state == 0) {
970 const Company *cc;
971 FOR_ALL_COMPANIES(cc) {
972 if (cc != c && cc->colour == colour) return CommandError();
976 if (flags & DC_EXEC) {
977 switch (state) {
978 case 0:
979 c->livery[scheme].colour1 = colour;
981 /* If setting the first colour of the default scheme, adjust the
982 * original and cached company colours too. */
983 if (scheme == LS_DEFAULT) {
984 _company_colours[_current_company] = colour;
985 c->colour = colour;
986 CompanyAdminUpdate(c);
988 break;
990 case 1:
991 c->livery[scheme].colour2 = colour;
992 break;
994 case 2:
995 c->livery[scheme].in_use = colour != 0;
997 /* Now handle setting the default scheme's in_use flag.
998 * This is different to the other schemes, as it signifies if any
999 * scheme is active at all. If this flag is not set, then no
1000 * processing of vehicle types occurs at all, and only the default
1001 * colours will be used. */
1003 /* If enabling a scheme, set the default scheme to be in use too */
1004 if (colour != 0) {
1005 c->livery[LS_DEFAULT].in_use = true;
1006 break;
1009 /* Else loop through all schemes to see if any are left enabled.
1010 * If not, disable the default scheme too. */
1011 c->livery[LS_DEFAULT].in_use = false;
1012 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1013 if (c->livery[scheme].in_use) {
1014 c->livery[LS_DEFAULT].in_use = true;
1015 break;
1018 break;
1020 default:
1021 break;
1023 ResetVehicleColourMap();
1024 MarkWholeScreenDirty();
1026 /* All graph related to companies use the company colour. */
1027 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1028 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1029 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1030 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1031 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1032 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1033 /* The smallmap owner view also stores the company colours. */
1034 BuildOwnerLegend();
1035 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1037 /* Company colour data is indirectly cached. */
1038 Vehicle *v;
1039 FOR_ALL_VEHICLES(v) {
1040 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1043 extern void UpdateObjectColours(const Company *c);
1044 UpdateObjectColours(c);
1046 return CommandCost();
1050 * Is the given name in use as name of a company?
1051 * @param name Name to search.
1052 * @return \c true if the name us unique (that is, not in use), else \c false.
1054 static bool IsUniqueCompanyName(const char *name)
1056 const Company *c;
1058 FOR_ALL_COMPANIES(c) {
1059 if (c->name != nullptr && strcmp(c->name, name) == 0) return false;
1062 return true;
1066 * Change the name of the company.
1067 * @param tile unused
1068 * @param flags operation to perform
1069 * @param p1 unused
1070 * @param p2 unused
1071 * @param text the new name or an empty string when resetting to the default
1072 * @return the cost of this operation or an error
1074 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1076 bool reset = StrEmpty(text);
1078 if (!reset) {
1079 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CommandError();
1080 if (!IsUniqueCompanyName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1083 if (flags & DC_EXEC) {
1084 Company *c = Company::Get(_current_company);
1085 free(c->name);
1086 c->name = reset ? nullptr : stredup(text);
1087 MarkWholeScreenDirty();
1088 CompanyAdminUpdate(c);
1091 return CommandCost();
1095 * Is the given name in use as president name of a company?
1096 * @param name Name to search.
1097 * @return \c true if the name us unique (that is, not in use), else \c false.
1099 static bool IsUniquePresidentName(const char *name)
1101 const Company *c;
1103 FOR_ALL_COMPANIES(c) {
1104 if (c->president_name != nullptr && strcmp(c->president_name, name) == 0) return false;
1107 return true;
1111 * Change the name of the president.
1112 * @param tile unused
1113 * @param flags operation to perform
1114 * @param p1 unused
1115 * @param p2 unused
1116 * @param text the new name or an empty string when resetting to the default
1117 * @return the cost of this operation or an error
1119 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1121 bool reset = StrEmpty(text);
1123 if (!reset) {
1124 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CommandError();
1125 if (!IsUniquePresidentName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1128 if (flags & DC_EXEC) {
1129 Company *c = Company::Get(_current_company);
1130 free(c->president_name);
1132 if (reset) {
1133 c->president_name = nullptr;
1134 } else {
1135 c->president_name = stredup(text);
1137 if (c->name_1 == STR_SV_UNNAMED && c->name == nullptr) {
1138 char buf[80];
1140 seprintf(buf, lastof(buf), "%s Transport", text);
1141 DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
1145 MarkWholeScreenDirty();
1146 CompanyAdminUpdate(c);
1149 return CommandCost();
1153 * Get the service interval for the given company and vehicle type.
1154 * @param c The company, or nullptr for client-default settings.
1155 * @param type The vehicle type to get the interval for.
1156 * @return The service interval.
1158 int CompanyServiceInterval(const Company *c, VehicleType type)
1160 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1161 switch (type) {
1162 default: NOT_REACHED();
1163 case VEH_TRAIN: return vds->servint_trains;
1164 case VEH_ROAD: return vds->servint_roadveh;
1165 case VEH_AIRCRAFT: return vds->servint_aircraft;
1166 case VEH_SHIP: return vds->servint_ships;
1170 char *CompanyInfrastructure::Dump(char *buffer, const char *last) const
1172 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
1173 if (rail[rt]) buffer += seprintf(buffer, last, "Rail: %s: %u\n", GetStringPtr(GetRailTypeInfo(rt)->strings.name), rail[rt]);
1175 buffer += seprintf(buffer, last, "Signal: %u\n", signal);
1176 buffer += seprintf(buffer, last, "Road: %u\n", road[ROADTYPE_ROAD]);
1177 buffer += seprintf(buffer, last, "Tram: %u\n", road[ROADTYPE_TRAM]);
1178 buffer += seprintf(buffer, last, "Water: %u\n", water);
1179 buffer += seprintf(buffer, last, "Station: %u\n", station);
1180 buffer += seprintf(buffer, last, "Airport: %u\n", airport);
1182 return buffer;