Update map documentation
[openttd-joker.git] / src / company_cmd.cpp
blobf54a44af66a48767ec4a95a04aff099cf8fe55e9
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 "road.h"
32 #include "core/pool_func.hpp"
33 #include "settings_func.h"
34 #include "vehicle_base.h"
35 #include "vehicle_func.h"
36 #include "smallmap_gui.h"
37 #include "game/game.hpp"
38 #include "goal_base.h"
39 #include "story_base.h"
40 #include "zoning.h"
42 #include "table/strings.h"
44 #include "safeguards.h"
46 void ClearEnginesHiddenFlagOfCompany(CompanyID cid);
48 CompanyByte _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
49 CompanyByte _current_company; ///< Company currently doing an action.
50 Colours _company_colours[MAX_COMPANIES]; ///< NOSAVE: can be determined from company structs.
51 CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
52 uint _next_competitor_start; ///< the number of ticks before the next AI is started
53 uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
55 CompanyPool _company_pool("Company"); ///< Pool of companies.
56 INSTANTIATE_POOL_METHODS(Company)
58 /**
59 * Constructor.
60 * @param name_1 Name of the company.
61 * @param is_ai A computer program is running for this company.
63 Company::Company(uint16 name_1, bool is_ai)
65 this->name_1 = name_1;
66 this->location_of_HQ = INVALID_TILE;
67 this->is_ai = is_ai;
68 this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
69 this->clear_limit = _settings_game.construction.clear_frame_burst << 16;
70 this->tree_limit = _settings_game.construction.tree_frame_burst << 16;
72 for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
73 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
76 /** Destructor. */
77 Company::~Company()
79 if (CleaningPool()) return;
81 DeleteCompanyWindows(this->index);
84 /**
85 * Invalidating some stuff after removing item from the pool.
86 * @param index index of deleted item
88 void Company::PostDestructor(size_t index)
90 InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
91 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
92 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
93 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
94 /* If the currently shown error message has this company in it, then close it. */
95 InvalidateWindowData(WC_ERRMSG, 0);
98 /**
99 * Sets the local company and updates the settings that are set on a
100 * per-company basis to reflect the core's state in the GUI.
101 * @param new_company the new company
102 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
104 void SetLocalCompany(CompanyID new_company)
106 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
107 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
109 #ifdef ENABLE_NETWORK
110 /* Delete the chat window, if you were team chatting. */
111 InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
112 #endif
114 assert(IsLocalCompany());
116 _current_company = _local_company = new_company;
118 /* Delete any construction windows... */
119 DeleteConstructionWindows();
121 /* ... and redraw the whole screen. */
122 MarkWholeScreenDirty();
123 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
124 ClearZoningCaches();
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) SetWindowDirty(WC_STATUS_BAR, 0);
189 SetWindowDirty(WC_FINANCES, cid);
193 * Verify whether the company can pay the bill.
194 * @param cost [inout] 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, 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_INC |
224 1 << EXPENSES_ROADVEH_INC |
225 1 << EXPENSES_AIRCRAFT_INC |
226 1 << EXPENSES_SHIP_INC, 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_INT, 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(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, 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 Company *c;
271 FOR_ALL_COMPANIES(c) {
272 c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
273 c->clear_limit = min(c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint32)_settings_game.construction.clear_frame_burst << 16);
274 c->tree_limit = min(c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint32)_settings_game.construction.tree_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 CommandError(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 CommandError(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 == nullptr && 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 Company *cc;
368 FOR_ALL_COMPANIES(cc) {
369 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
372 GetString(buffer, str, lastof(buffer));
373 if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
375 set_name:;
376 c->name_1 = str;
377 c->name_2 = strp;
379 MarkWholeScreenDirty();
381 if (c->is_ai) {
382 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
383 cni->FillData(c);
384 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
385 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
386 SetDParamStr(2, cni->company_name);
387 SetDParam(3, t->index);
388 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
390 return;
392 bad_town_name:;
394 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
395 str = SPECSTR_ANDCO_NAME;
396 strp = c->president_name_2;
397 goto set_name;
398 } else {
399 str = SPECSTR_ANDCO_NAME;
400 strp = Random();
401 goto verify_name;
405 /** Sorting weights for the company colours. */
406 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
407 /** Similar colours, so we can try to prevent same coloured companies. */
408 static const Colours _similar_colour[COLOUR_END][2] = {
409 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
410 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
411 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
412 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
413 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
414 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
415 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
416 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
417 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
418 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
419 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
420 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
421 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
422 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
423 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
424 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
428 * Generate a company colour.
429 * @return Generated company colour.
431 static Colours GenerateCompanyColour()
433 Colours colours[COLOUR_END];
435 /* Initialize array */
436 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
438 /* And randomize it */
439 for (uint i = 0; i < 100; i++) {
440 uint r = Random();
441 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
444 /* Bubble sort it according to the values in table 1 */
445 for (uint i = 0; i < COLOUR_END; i++) {
446 for (uint j = 1; j < COLOUR_END; j++) {
447 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
448 Swap(colours[j - 1], colours[j]);
453 /* Move the colours that look similar to each company's colour to the side */
454 Company *c;
455 FOR_ALL_COMPANIES(c) {
456 Colours pcolour = (Colours)c->colour;
458 for (uint i = 0; i < COLOUR_END; i++) {
459 if (colours[i] == pcolour) {
460 colours[i] = INVALID_COLOUR;
461 break;
465 for (uint j = 0; j < 2; j++) {
466 Colours similar = _similar_colour[pcolour][j];
467 if (similar == INVALID_COLOUR) break;
469 for (uint i = 1; i < COLOUR_END; i++) {
470 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
475 /* Return the first available colour */
476 for (uint i = 0; i < COLOUR_END; i++) {
477 if (colours[i] != INVALID_COLOUR) return colours[i];
480 NOT_REACHED();
484 * Generate a random president name of a company.
485 * @param c Company that needs a new president name.
487 static void GeneratePresidentName(Company *c)
489 for (;;) {
490 restart:;
491 c->president_name_2 = Random();
492 c->president_name_1 = SPECSTR_PRESIDENT_NAME;
494 /* Reserve space for extra unicode character. We need to do this to be able
495 * to detect too long president name. */
496 char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
497 SetDParam(0, c->index);
498 GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
499 if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
501 Company *cc;
502 FOR_ALL_COMPANIES(cc) {
503 if (c != cc) {
504 /* Reserve extra space so even overlength president names can be compared. */
505 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
506 SetDParam(0, cc->index);
507 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
508 if (strcmp(buffer2, buffer) == 0) goto restart;
511 return;
516 * Reset the livery schemes to the company's primary colour.
517 * This is used on loading games without livery information and on new company start up.
518 * @param c Company to reset.
520 void ResetCompanyLivery(Company *c)
522 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
523 c->livery[scheme].in_use = false;
524 c->livery[scheme].colour1 = c->colour;
525 c->livery[scheme].colour2 = c->colour;
530 * Create a new company and sets all company variables default values
532 * @param is_ai is an AI company?
533 * @param company CompanyID to use for the new company
534 * @return the company struct
536 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
538 if (!Company::CanAllocateItem()) return nullptr;
540 /* we have to generate colour before this company is valid */
541 Colours colour = GenerateCompanyColour();
543 Company *c;
544 if (company == INVALID_COMPANY) {
545 c = new Company(STR_SV_UNNAMED, is_ai);
546 } else {
547 if (Company::IsValidID(company)) return nullptr;
548 c = new (company) Company(STR_SV_UNNAMED, is_ai);
551 c->colour = colour;
553 ResetCompanyLivery(c);
554 _company_colours[c->index] = (Colours)c->colour;
556 c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
558 c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
560 c->avail_railtypes = GetCompanyRailtypes(c->index);
561 c->avail_roadtypes[ROADTYPE_ROAD] = GetCompanyRoadtypes(c->index, ROADTYPE_ROAD);
562 c->avail_roadtypes[ROADTYPE_TRAM] = GetCompanyRoadtypes(c->index, ROADTYPE_TRAM);
563 c->inaugurated_year = _cur_year;
564 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false); // create a random company manager face
566 SetDefaultCompanySettings(c->index);
567 ClearEnginesHiddenFlagOfCompany(c->index);
569 GeneratePresidentName(c);
571 SetWindowDirty(WC_GRAPH_LEGEND, 0);
572 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
573 SetWindowDirty(WC_CLIENT_LIST, 0);
574 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
575 BuildOwnerLegend();
576 InvalidateWindowData(WC_SMALLMAP, 0, 1);
578 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
580 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
581 Game::NewEvent(new ScriptEventCompanyNew(c->index));
583 if (!is_ai) UpdateAllTownVirtCoords();
585 return c;
588 /** Start the next competitor now. */
589 void StartupCompanies()
591 _next_competitor_start = 0;
594 /** Start a new competitor company if possible. */
595 static void MaybeStartNewCompany()
597 #ifdef ENABLE_NETWORK
598 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
599 #endif /* ENABLE_NETWORK */
601 Company *c;
603 /* count number of competitors */
604 uint n = 0;
605 FOR_ALL_COMPANIES(c) {
606 if (c->is_ai) n++;
609 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
610 /* Send a command to all clients to start up a new AI.
611 * Works fine for Multiplayer and Singleplayer */
612 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
616 /** Initialize the pool of companies. */
617 void InitializeCompanies()
619 _cur_company_tick_index = 0;
623 * May company \a cbig buy company \a csmall?
624 * @param cbig Company buying \a csmall.
625 * @param csmall Company getting bought.
626 * @return Return \c true if it is allowed.
628 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
630 const Company *c1 = Company::Get(cbig);
631 const Company *c2 = Company::Get(csmall);
633 /* Do the combined vehicle counts stay within the limits? */
634 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
635 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
636 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
637 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
641 * Handle the bankruptcy take over of a company.
642 * Companies going bankrupt will ask the other companies in order of their
643 * performance rating, so better performing companies get the 'do you want to
644 * merge with Y' question earlier. The question will then stay till either the
645 * company has gone bankrupt or got merged with a company.
647 * @param c the company that is going bankrupt.
649 static void HandleBankruptcyTakeover(Company *c)
651 /* Amount of time out for each company to take over a company;
652 * Timeout is a quarter (3 months of 30 days) divided over the
653 * number of companies. The minimum number of days in a quarter
654 * is 90: 31 in January, 28 in February and 31 in March.
655 * Note that the company going bankrupt can't buy itself. */
656 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
658 assert(c->bankrupt_asked != 0);
660 /* We're currently asking some company to buy 'us' */
661 if (c->bankrupt_timeout != 0) {
662 c->bankrupt_timeout -= MAX_COMPANIES;
663 if (c->bankrupt_timeout > 0) return;
664 c->bankrupt_timeout = 0;
666 return;
669 /* Did we ask everyone for bankruptcy? If so, bail out. */
670 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
672 Company *c2, *best = nullptr;
673 int32 best_performance = -1;
675 /* Ask the company with the highest performance history first */
676 FOR_ALL_COMPANIES(c2) {
677 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
678 !HasBit(c->bankrupt_asked, c2->index) &&
679 best_performance < c2->old_economy[1].performance_history &&
680 MayCompanyTakeOver(c2->index, c->index)) {
681 best_performance = c2->old_economy[1].performance_history;
682 best = c2;
686 /* Asked all companies? */
687 if (best_performance == -1) {
688 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
689 return;
692 SetBit(c->bankrupt_asked, best->index);
694 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
695 if (best->is_ai) {
696 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
697 } else if (IsInteractiveCompany(best->index)) {
698 ShowBuyCompanyDialog(c->index);
702 /** Called every tick for updating some company info. */
703 void OnTick_Companies()
705 if (_game_mode == GM_EDITOR) return;
707 Company *c = Company::GetIfValid(_cur_company_tick_index);
708 if (c != nullptr) {
709 if (c->name_1 != 0) GenerateCompanyName(c);
710 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
713 if (_next_competitor_start == 0) {
714 _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
717 if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
718 MaybeStartNewCompany();
721 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
725 * A year has passed, update the economic data of all companies, and perhaps show the
726 * financial overview window of the local company.
728 void CompaniesYearlyLoop()
730 Company *c;
732 /* Copy statistics */
733 FOR_ALL_COMPANIES(c) {
734 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
735 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
736 SetWindowDirty(WC_FINANCES, c->index);
739 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
740 ShowCompanyFinances(_local_company);
741 c = Company::Get(_local_company);
742 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
743 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
744 } else {
745 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
751 * Fill the CompanyNewsInformation struct with the required data.
752 * @param c the current company.
753 * @param other the other company (use \c nullptr if not relevant).
755 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
757 SetDParam(0, c->index);
758 GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
760 if (other == nullptr) {
761 *this->other_company_name = '\0';
762 } else {
763 SetDParam(0, other->index);
764 GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
765 c = other;
768 SetDParam(0, c->index);
769 GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
771 this->colour = c->colour;
772 this->face = c->face;
777 * Called whenever company related information changes in order to notify admins.
778 * @param company The company data changed of.
780 void CompanyAdminUpdate(const Company *company)
782 #ifdef ENABLE_NETWORK
783 if (_network_server) NetworkAdminCompanyUpdate(company);
784 #endif /* ENABLE_NETWORK */
788 * Called whenever a company is removed in order to notify admins.
789 * @param company_id The company that was removed.
790 * @param reason The reason the company was removed.
792 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
794 #ifdef ENABLE_NETWORK
795 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
796 #endif /* ENABLE_NETWORK */
800 * Control the companies: add, delete, etc.
801 * @param tile unused
802 * @param flags operation to perform
803 * @param p1 various functionality
804 * - bits 0..15:
805 * = 0 - create a new company
806 * = 1 - create a new AI company
807 * = 2 - delete a company
808 * - bits 16..24: CompanyID
809 * @param p2 ClientID
810 * @param text unused
811 * @return the cost of this operation or an error
813 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
815 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
816 CompanyID company_id = (CompanyID)GB(p1, 16, 8);
817 #ifdef ENABLE_NETWORK
818 ClientID client_id = (ClientID)p2;
819 #endif /* ENABLE_NETWORK */
821 switch (GB(p1, 0, 16)) {
822 case 0: { // Create a new company
823 /* This command is only executed in a multiplayer game */
824 if (!_networking) return CommandError();
826 #ifdef ENABLE_NETWORK
827 /* Has the network client a correct ClientIndex? */
828 if (!(flags & DC_EXEC)) return CommandCost();
829 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
830 #ifndef DEBUG_DUMP_COMMANDS
831 /* When replaying the client ID is not a valid client; there
832 * are actually no clients at all. However, the company has to
833 * be created, otherwise we cannot rerun the game properly.
834 * So only allow a nullptr client info in that case. */
835 if (ci == nullptr) return CommandCost();
836 #endif /* NOT DEBUG_DUMP_COMMANDS */
838 /* Delete multiplayer progress bar */
839 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
841 Company *c = DoStartupNewCompany(false);
843 /* A new company could not be created, revert to being a spectator */
844 if (c == nullptr) {
845 if (_network_server) {
846 ci->client_playas = COMPANY_SPECTATOR;
847 NetworkUpdateClientInfo(ci->client_id);
849 break;
852 /* This is the client (or non-dedicated server) who wants a new company */
853 if (client_id == _network_own_client_id) {
854 assert(_local_company == COMPANY_SPECTATOR);
855 SetLocalCompany(c->index);
856 if (!StrEmpty(_settings_client.network.default_company_pass)) {
857 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
860 /* Now that we have a new company, broadcast our company settings to
861 * all clients so everything is in sync */
862 SyncCompanySettings();
864 MarkWholeScreenDirty();
867 NetworkServerNewCompany(c, ci);
868 #endif /* ENABLE_NETWORK */
869 break;
872 case 1: { // Make a new AI company
873 if (!(flags & DC_EXEC)) return CommandCost();
875 if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CommandError();
876 Company *c = DoStartupNewCompany(true, company_id);
877 #ifdef ENABLE_NETWORK
878 if (c != nullptr) NetworkServerNewCompany(c, nullptr);
879 #endif /* ENABLE_NETWORK */
880 break;
883 case 2: { // Delete a company
884 CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
885 if (reason >= CRR_END) return CommandError();
887 Company *c = Company::GetIfValid(company_id);
888 if (c == nullptr) return CommandError();
890 if (!(flags & DC_EXEC)) return CommandCost();
892 /* Delete any open window of the company */
893 DeleteCompanyWindows(c->index);
894 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
895 cni->FillData(c);
897 /* Show the bankrupt news */
898 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
899 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
900 SetDParamStr(2, cni->company_name);
901 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
903 /* Remove the company */
904 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
905 if (c->is_ai) AI::Stop(c->index);
907 CompanyID c_index = c->index;
908 delete c;
909 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
910 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
911 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
913 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
914 break;
917 default: return CommandError();
920 InvalidateWindowClassesData(WC_GAME_OPTIONS);
921 InvalidateWindowClassesData(WC_AI_SETTINGS);
922 InvalidateWindowClassesData(WC_AI_LIST);
924 return CommandCost();
928 * Change the company manager's face.
929 * @param tile unused
930 * @param flags operation to perform
931 * @param p1 unused
932 * @param p2 face bitmasked
933 * @param text unused
934 * @return the cost of this operation or an error
936 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
938 CompanyManagerFace cmf = (CompanyManagerFace)p2;
940 if (!IsValidCompanyManagerFace(cmf)) return CommandError();
942 if (flags & DC_EXEC) {
943 Company::Get(_current_company)->face = cmf;
944 MarkWholeScreenDirty();
946 return CommandCost();
950 * Change the company's company-colour
951 * @param tile unused
952 * @param flags operation to perform
953 * @param p1 bitstuffed:
954 * p1 bits 0-7 scheme to set
955 * p1 bits 8-9 set in use state or first/second colour
956 * @param p2 new colour for vehicles, property, etc.
957 * @param text unused
958 * @return the cost of this operation or an error
960 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
962 Colours colour = Extract<Colours, 0, 4>(p2);
963 LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
964 byte state = GB(p1, 8, 2);
966 if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CommandError();
968 Company *c = Company::Get(_current_company);
970 /* Ensure no two companies have the same primary colour */
971 if (scheme == LS_DEFAULT && state == 0) {
972 const Company *cc;
973 FOR_ALL_COMPANIES(cc) {
974 if (cc != c && cc->colour == colour) return CommandError();
978 if (flags & DC_EXEC) {
979 switch (state) {
980 case 0:
981 c->livery[scheme].colour1 = colour;
983 /* If setting the first colour of the default scheme, adjust the
984 * original and cached company colours too. */
985 if (scheme == LS_DEFAULT) {
986 _company_colours[_current_company] = colour;
987 c->colour = colour;
988 CompanyAdminUpdate(c);
990 break;
992 case 1:
993 c->livery[scheme].colour2 = colour;
994 break;
996 case 2:
997 c->livery[scheme].in_use = colour != 0;
999 /* Now handle setting the default scheme's in_use flag.
1000 * This is different to the other schemes, as it signifies if any
1001 * scheme is active at all. If this flag is not set, then no
1002 * processing of vehicle types occurs at all, and only the default
1003 * colours will be used. */
1005 /* If enabling a scheme, set the default scheme to be in use too */
1006 if (colour != 0) {
1007 c->livery[LS_DEFAULT].in_use = true;
1008 break;
1011 /* Else loop through all schemes to see if any are left enabled.
1012 * If not, disable the default scheme too. */
1013 c->livery[LS_DEFAULT].in_use = false;
1014 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1015 if (c->livery[scheme].in_use) {
1016 c->livery[LS_DEFAULT].in_use = true;
1017 break;
1020 break;
1022 default:
1023 break;
1025 ResetVehicleColourMap();
1026 MarkWholeScreenDirty();
1028 /* All graph related to companies use the company colour. */
1029 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1030 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1031 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1032 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1033 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1034 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1035 /* The smallmap owner view also stores the company colours. */
1036 BuildOwnerLegend();
1037 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1039 /* Company colour data is indirectly cached. */
1040 Vehicle *v;
1041 FOR_ALL_VEHICLES(v) {
1042 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1045 extern void UpdateObjectColours(const Company *c);
1046 UpdateObjectColours(c);
1048 return CommandCost();
1052 * Is the given name in use as name of a company?
1053 * @param name Name to search.
1054 * @return \c true if the name us unique (that is, not in use), else \c false.
1056 static bool IsUniqueCompanyName(const char *name)
1058 const Company *c;
1060 FOR_ALL_COMPANIES(c) {
1061 if (c->name != nullptr && strcmp(c->name, name) == 0) return false;
1064 return true;
1068 * Change the name of the company.
1069 * @param tile unused
1070 * @param flags operation to perform
1071 * @param p1 unused
1072 * @param p2 unused
1073 * @param text the new name or an empty string when resetting to the default
1074 * @return the cost of this operation or an error
1076 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1078 bool reset = StrEmpty(text);
1080 if (!reset) {
1081 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CommandError();
1082 if (!IsUniqueCompanyName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1085 if (flags & DC_EXEC) {
1086 Company *c = Company::Get(_current_company);
1087 free(c->name);
1088 c->name = reset ? nullptr : stredup(text);
1089 MarkWholeScreenDirty();
1090 CompanyAdminUpdate(c);
1093 return CommandCost();
1097 * Is the given name in use as president name of a company?
1098 * @param name Name to search.
1099 * @return \c true if the name us unique (that is, not in use), else \c false.
1101 static bool IsUniquePresidentName(const char *name)
1103 const Company *c;
1105 FOR_ALL_COMPANIES(c) {
1106 if (c->president_name != nullptr && strcmp(c->president_name, name) == 0) return false;
1109 return true;
1113 * Change the name of the president.
1114 * @param tile unused
1115 * @param flags operation to perform
1116 * @param p1 unused
1117 * @param p2 unused
1118 * @param text the new name or an empty string when resetting to the default
1119 * @return the cost of this operation or an error
1121 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1123 bool reset = StrEmpty(text);
1125 if (!reset) {
1126 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CommandError();
1127 if (!IsUniquePresidentName(text)) return CommandError(STR_ERROR_NAME_MUST_BE_UNIQUE);
1130 if (flags & DC_EXEC) {
1131 Company *c = Company::Get(_current_company);
1132 free(c->president_name);
1134 if (reset) {
1135 c->president_name = nullptr;
1136 } else {
1137 c->president_name = stredup(text);
1139 if (c->name_1 == STR_SV_UNNAMED && c->name == nullptr) {
1140 char buf[80];
1142 seprintf(buf, lastof(buf), "%s Transport", text);
1143 DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
1147 MarkWholeScreenDirty();
1148 CompanyAdminUpdate(c);
1151 return CommandCost();
1155 * Get the service interval for the given company and vehicle type.
1156 * @param c The company, or nullptr for client-default settings.
1157 * @param type The vehicle type to get the interval for.
1158 * @return The service interval.
1160 int CompanyServiceInterval(const Company *c, VehicleType type)
1162 const VehicleDefaultSettings *vds = (c == nullptr) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1163 switch (type) {
1164 default: NOT_REACHED();
1165 case VEH_TRAIN: return vds->servint_trains;
1166 case VEH_ROAD: return vds->servint_roadveh;
1167 case VEH_AIRCRAFT: return vds->servint_aircraft;
1168 case VEH_SHIP: return vds->servint_ships;
1172 char *CompanyInfrastructure::Dump(char *buffer, const char *last) const
1174 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
1175 if (rail[rt]) buffer += seprintf(buffer, last, "Rail: %s: %u\n", GetStringPtr(GetRailTypeInfo(rt)->strings.name), rail[rt]);
1177 buffer += seprintf(buffer, last, "Signal: %u\n", signal);
1178 buffer += seprintf(buffer, last, "Road: %u\n", road[ROADTYPE_ROAD]);
1179 buffer += seprintf(buffer, last, "Tram: %u\n", road[ROADTYPE_TRAM]);
1180 buffer += seprintf(buffer, last, "Water: %u\n", water);
1181 buffer += seprintf(buffer, last, "Station: %u\n", station);
1182 buffer += seprintf(buffer, last, "Airport: %u\n", airport);
1184 return buffer;