(svn r27953) -Cleanup: Adjust other languages for r27952
[openttd.git] / src / company_cmd.cpp
blobee2ed13355cf3e6cd41f9e454c9380b406e8e04d
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"
40 #include "table/strings.h"
42 #include "safeguards.h"
44 void ClearEnginesHiddenFlagOfCompany(CompanyID cid);
46 CompanyByte _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
47 CompanyByte _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 = _settings_game.construction.terraform_frame_burst << 16;
67 this->clear_limit = _settings_game.construction.clear_frame_burst << 16;
68 this->tree_limit = _settings_game.construction.tree_frame_burst << 16;
70 for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
71 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
74 /** Destructor. */
75 Company::~Company()
77 if (CleaningPool()) return;
79 DeleteCompanyWindows(this->index);
82 /**
83 * Invalidating some stuff after removing item from the pool.
84 * @param index index of deleted item
86 void Company::PostDestructor(size_t index)
88 InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
89 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
90 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
91 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
92 /* If the currently shown error message has this company in it, then close it. */
93 InvalidateWindowData(WC_ERRMSG, 0);
96 /**
97 * Sets the local company and updates the settings that are set on a
98 * per-company basis to reflect the core's state in the GUI.
99 * @param new_company the new company
100 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
102 void SetLocalCompany(CompanyID new_company)
104 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
105 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
107 #ifdef ENABLE_NETWORK
108 /* Delete the chat window, if you were team chatting. */
109 InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
110 #endif
112 assert(IsLocalCompany());
114 _current_company = _local_company = new_company;
116 /* Delete any construction windows... */
117 DeleteConstructionWindows();
119 /* ... and redraw the whole screen. */
120 MarkWholeScreenDirty();
121 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
125 * Get the colour for DrawString-subroutines which matches the colour of the company.
126 * @param company Company to get the colour of.
127 * @return Colour of \a company.
129 TextColour GetDrawStringCompanyColour(CompanyID company)
131 if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
132 return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
136 * Draw the icon of a company.
137 * @param c Company that needs its icon drawn.
138 * @param x Horizontal coordinate of the icon.
139 * @param y Vertical coordinate of the icon.
141 void DrawCompanyIcon(CompanyID c, int x, int y)
143 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
147 * Checks whether a company manager's face is a valid encoding.
148 * Unused bits are not enforced to be 0.
149 * @param cmf the fact to check
150 * @return true if and only if the face is valid
152 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
154 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
156 GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
157 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
158 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
159 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
161 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
162 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
163 switch (cmfv) {
164 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
165 case CMFV_LIPS:
166 case CMFV_NOSE: if (has_moustache) continue; break;
167 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
168 case CMFV_GLASSES: if (!has_glasses) continue; break;
169 default: break;
171 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
174 return true;
178 * Refresh all windows owned by a company.
179 * @param company Company that changed, and needs its windows refreshed.
181 void InvalidateCompanyWindows(const Company *company)
183 CompanyID cid = company->index;
185 if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
186 SetWindowDirty(WC_FINANCES, cid);
190 * Verify whether the company can pay the bill.
191 * @param cost [inout] Money to pay, is changed to an error if the company does not have enough money.
192 * @return Function returns \c true if the company has enough money, else it returns \c false.
194 bool CheckCompanyHasMoney(CommandCost &cost)
196 if (cost.GetCost() > 0) {
197 const Company *c = Company::GetIfValid(_current_company);
198 if (c != NULL && cost.GetCost() > c->money) {
199 SetDParam(0, cost.GetCost());
200 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
201 return false;
204 return true;
208 * Deduct costs of a command from the money of a company.
209 * @param c Company to pay the bill.
210 * @param cost Money to pay.
212 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
214 if (cost.GetCost() == 0) return;
215 assert(cost.GetExpensesType() != INVALID_EXPENSES);
217 c->money -= cost.GetCost();
218 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
220 if (HasBit(1 << EXPENSES_TRAIN_INC |
221 1 << EXPENSES_ROADVEH_INC |
222 1 << EXPENSES_AIRCRAFT_INC |
223 1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
224 c->cur_economy.income -= cost.GetCost();
225 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
226 1 << EXPENSES_ROADVEH_RUN |
227 1 << EXPENSES_AIRCRAFT_RUN |
228 1 << EXPENSES_SHIP_RUN |
229 1 << EXPENSES_PROPERTY |
230 1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
231 c->cur_economy.expenses -= cost.GetCost();
234 InvalidateCompanyWindows(c);
238 * Subtract money from the #_current_company, if the company is valid.
239 * @param cost Money to pay.
241 void SubtractMoneyFromCompany(CommandCost cost)
243 Company *c = Company::GetIfValid(_current_company);
244 if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
248 * Subtract money from a company, including the money fraction.
249 * @param company Company paying the bill.
250 * @param cst Cost of a command.
252 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
254 Company *c = Company::Get(company);
255 byte m = c->money_fraction;
256 Money cost = cst.GetCost();
258 c->money_fraction = m - (byte)cost;
259 cost >>= 8;
260 if (c->money_fraction > m) cost++;
261 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
264 /** Update the landscaping limits per company. */
265 void UpdateLandscapingLimits()
267 Company *c;
268 FOR_ALL_COMPANIES(c) {
269 c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
270 c->clear_limit = min(c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint32)_settings_game.construction.clear_frame_burst << 16);
271 c->tree_limit = min(c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint32)_settings_game.construction.tree_frame_burst << 16);
276 * Set the right DParams to get the name of an owner.
277 * @param owner the owner to get the name of.
278 * @param tile optional tile to get the right town.
279 * @pre if tile == 0, then owner can't be OWNER_TOWN.
281 void GetNameOfOwner(Owner owner, TileIndex tile)
283 SetDParam(2, owner);
285 if (owner != OWNER_TOWN) {
286 if (!Company::IsValidID(owner)) {
287 SetDParam(0, STR_COMPANY_SOMEONE);
288 } else {
289 SetDParam(0, STR_COMPANY_NAME);
290 SetDParam(1, owner);
292 } else {
293 assert(tile != 0);
294 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
296 SetDParam(0, STR_TOWN_NAME);
297 SetDParam(1, t->index);
303 * Check whether the current owner owns something.
304 * If that isn't the case an appropriate error will be given.
305 * @param owner the owner of the thing to check.
306 * @param tile optional tile to get the right town.
307 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
308 * @return A succeeded command iff it's owned by the current company, else a failed command.
310 CommandCost CheckOwnership(Owner owner, TileIndex tile)
312 assert(owner < OWNER_END);
313 assert(owner != OWNER_TOWN || tile != 0);
315 if (owner == _current_company) return CommandCost();
317 GetNameOfOwner(owner, tile);
318 return_cmd_error(STR_ERROR_OWNED_BY);
322 * Check whether the current owner owns the stuff on
323 * the given tile. If that isn't the case an
324 * appropriate error will be given.
325 * @param tile the tile to check.
326 * @return A succeeded command iff it's owned by the current company, else a failed command.
328 CommandCost CheckTileOwnership(TileIndex tile)
330 Owner owner = GetTileOwner(tile);
332 assert(owner < OWNER_END);
334 if (owner == _current_company) return CommandCost();
336 /* no need to get the name of the owner unless we're the local company (saves some time) */
337 if (IsLocalCompany()) GetNameOfOwner(owner, tile);
338 return_cmd_error(STR_ERROR_OWNED_BY);
342 * Generate the name of a company from the last build coordinate.
343 * @param c Company to give a name.
345 static void GenerateCompanyName(Company *c)
347 /* Reserve space for extra unicode character. We need to do this to be able
348 * to detect too long company name. */
349 char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
351 if (c->name_1 != STR_SV_UNNAMED) return;
352 if (c->last_build_coordinate == 0) return;
354 Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
356 StringID str;
357 uint32 strp;
358 if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
359 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
360 strp = t->townnameparts;
362 verify_name:;
363 /* No companies must have this name already */
364 Company *cc;
365 FOR_ALL_COMPANIES(cc) {
366 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
369 GetString(buffer, str, lastof(buffer));
370 if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
372 set_name:;
373 c->name_1 = str;
374 c->name_2 = strp;
376 MarkWholeScreenDirty();
378 if (c->is_ai) {
379 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
380 cni->FillData(c);
381 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
382 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
383 SetDParamStr(2, cni->company_name);
384 SetDParam(3, t->index);
385 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
387 return;
389 bad_town_name:;
391 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
392 str = SPECSTR_ANDCO_NAME;
393 strp = c->president_name_2;
394 goto set_name;
395 } else {
396 str = SPECSTR_ANDCO_NAME;
397 strp = Random();
398 goto verify_name;
402 /** Sorting weights for the company colours. */
403 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
404 /** Similar colours, so we can try to prevent same coloured companies. */
405 static const Colours _similar_colour[COLOUR_END][2] = {
406 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
407 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
408 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
409 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
410 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
411 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
412 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
413 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
414 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
415 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
416 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
417 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
418 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
419 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
420 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
421 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
425 * Generate a company colour.
426 * @return Generated company colour.
428 static Colours GenerateCompanyColour()
430 Colours colours[COLOUR_END];
432 /* Initialize array */
433 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
435 /* And randomize it */
436 for (uint i = 0; i < 100; i++) {
437 uint r = Random();
438 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
441 /* Bubble sort it according to the values in table 1 */
442 for (uint i = 0; i < COLOUR_END; i++) {
443 for (uint j = 1; j < COLOUR_END; j++) {
444 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
445 Swap(colours[j - 1], colours[j]);
450 /* Move the colours that look similar to each company's colour to the side */
451 Company *c;
452 FOR_ALL_COMPANIES(c) {
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 Company *cc;
499 FOR_ALL_COMPANIES(cc) {
500 if (c != cc) {
501 /* Reserve extra space so even overlength president names can be compared. */
502 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
503 SetDParam(0, cc->index);
504 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
505 if (strcmp(buffer2, buffer) == 0) goto restart;
508 return;
513 * Reset the livery schemes to the company's primary colour.
514 * This is used on loading games without livery information and on new company start up.
515 * @param c Company to reset.
517 void ResetCompanyLivery(Company *c)
519 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
520 c->livery[scheme].in_use = false;
521 c->livery[scheme].colour1 = c->colour;
522 c->livery[scheme].colour2 = c->colour;
527 * Create a new company and sets all company variables default values
529 * @param is_ai is an AI company?
530 * @param company CompanyID to use for the new company
531 * @return the company struct
533 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
535 if (!Company::CanAllocateItem()) return NULL;
537 /* we have to generate colour before this company is valid */
538 Colours colour = GenerateCompanyColour();
540 Company *c;
541 if (company == INVALID_COMPANY) {
542 c = new Company(STR_SV_UNNAMED, is_ai);
543 } else {
544 if (Company::IsValidID(company)) return NULL;
545 c = new (company) Company(STR_SV_UNNAMED, is_ai);
548 c->colour = colour;
550 ResetCompanyLivery(c);
551 _company_colours[c->index] = (Colours)c->colour;
553 c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
555 c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
557 c->avail_railtypes = GetCompanyRailtypes(c->index);
558 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
559 c->inaugurated_year = _cur_year;
560 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false); // create a random company manager face
562 SetDefaultCompanySettings(c->index);
563 ClearEnginesHiddenFlagOfCompany(c->index);
565 GeneratePresidentName(c);
567 SetWindowDirty(WC_GRAPH_LEGEND, 0);
568 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
569 SetWindowDirty(WC_CLIENT_LIST, 0);
570 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
571 BuildOwnerLegend();
572 InvalidateWindowData(WC_SMALLMAP, 0, 1);
574 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
576 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
577 Game::NewEvent(new ScriptEventCompanyNew(c->index));
579 return c;
582 /** Start the next competitor now. */
583 void StartupCompanies()
585 _next_competitor_start = 0;
588 /** Start a new competitor company if possible. */
589 static void MaybeStartNewCompany()
591 #ifdef ENABLE_NETWORK
592 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
593 #endif /* ENABLE_NETWORK */
595 Company *c;
597 /* count number of competitors */
598 uint n = 0;
599 FOR_ALL_COMPANIES(c) {
600 if (c->is_ai) n++;
603 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
604 /* Send a command to all clients to start up a new AI.
605 * Works fine for Multiplayer and Singleplayer */
606 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
610 /** Initialize the pool of companies. */
611 void InitializeCompanies()
613 _cur_company_tick_index = 0;
617 * May company \a cbig buy company \a csmall?
618 * @param cbig Company buying \a csmall.
619 * @param csmall Company getting bought.
620 * @return Return \c true if it is allowed.
622 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
624 const Company *c1 = Company::Get(cbig);
625 const Company *c2 = Company::Get(csmall);
627 /* Do the combined vehicle counts stay within the limits? */
628 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
629 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
630 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
631 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
635 * Handle the bankruptcy take over of a company.
636 * Companies going bankrupt will ask the other companies in order of their
637 * performance rating, so better performing companies get the 'do you want to
638 * merge with Y' question earlier. The question will then stay till either the
639 * company has gone bankrupt or got merged with a company.
641 * @param c the company that is going bankrupt.
643 static void HandleBankruptcyTakeover(Company *c)
645 /* Amount of time out for each company to take over a company;
646 * Timeout is a quarter (3 months of 30 days) divided over the
647 * number of companies. The minimum number of days in a quarter
648 * is 90: 31 in January, 28 in February and 31 in March.
649 * Note that the company going bankrupt can't buy itself. */
650 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
652 assert(c->bankrupt_asked != 0);
654 /* We're currently asking some company to buy 'us' */
655 if (c->bankrupt_timeout != 0) {
656 c->bankrupt_timeout -= MAX_COMPANIES;
657 if (c->bankrupt_timeout > 0) return;
658 c->bankrupt_timeout = 0;
660 return;
663 /* Did we ask everyone for bankruptcy? If so, bail out. */
664 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
666 Company *c2, *best = NULL;
667 int32 best_performance = -1;
669 /* Ask the company with the highest performance history first */
670 FOR_ALL_COMPANIES(c2) {
671 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
672 !HasBit(c->bankrupt_asked, c2->index) &&
673 best_performance < c2->old_economy[1].performance_history &&
674 MayCompanyTakeOver(c2->index, c->index)) {
675 best_performance = c2->old_economy[1].performance_history;
676 best = c2;
680 /* Asked all companies? */
681 if (best_performance == -1) {
682 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
683 return;
686 SetBit(c->bankrupt_asked, best->index);
688 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
689 if (best->is_ai) {
690 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
691 } else if (IsInteractiveCompany(best->index)) {
692 ShowBuyCompanyDialog(c->index);
696 /** Called every tick for updating some company info. */
697 void OnTick_Companies()
699 if (_game_mode == GM_EDITOR) return;
701 Company *c = Company::GetIfValid(_cur_company_tick_index);
702 if (c != NULL) {
703 if (c->name_1 != 0) GenerateCompanyName(c);
704 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
707 if (_next_competitor_start == 0) {
708 _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
711 if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
712 MaybeStartNewCompany();
715 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
719 * A year has passed, update the economic data of all companies, and perhaps show the
720 * financial overview window of the local company.
722 void CompaniesYearlyLoop()
724 Company *c;
726 /* Copy statistics */
727 FOR_ALL_COMPANIES(c) {
728 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
729 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
730 SetWindowDirty(WC_FINANCES, c->index);
733 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
734 ShowCompanyFinances(_local_company);
735 c = Company::Get(_local_company);
736 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
737 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
738 } else {
739 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
745 * Fill the CompanyNewsInformation struct with the required data.
746 * @param c the current company.
747 * @param other the other company (use \c NULL if not relevant).
749 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
751 SetDParam(0, c->index);
752 GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
754 if (other == NULL) {
755 *this->other_company_name = '\0';
756 } else {
757 SetDParam(0, other->index);
758 GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
759 c = other;
762 SetDParam(0, c->index);
763 GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
765 this->colour = c->colour;
766 this->face = c->face;
771 * Called whenever company related information changes in order to notify admins.
772 * @param company The company data changed of.
774 void CompanyAdminUpdate(const Company *company)
776 #ifdef ENABLE_NETWORK
777 if (_network_server) NetworkAdminCompanyUpdate(company);
778 #endif /* ENABLE_NETWORK */
782 * Called whenever a company is removed in order to notify admins.
783 * @param company_id The company that was removed.
784 * @param reason The reason the company was removed.
786 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
788 #ifdef ENABLE_NETWORK
789 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
790 #endif /* ENABLE_NETWORK */
794 * Control the companies: add, delete, etc.
795 * @param tile unused
796 * @param flags operation to perform
797 * @param p1 various functionality
798 * - bits 0..15:
799 * = 0 - create a new company
800 * = 1 - create a new AI company
801 * = 2 - delete a company
802 * - bits 16..24: CompanyID
803 * @param p2 ClientID
804 * @param text unused
805 * @return the cost of this operation or an error
807 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
809 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
810 CompanyID company_id = (CompanyID)GB(p1, 16, 8);
811 #ifdef ENABLE_NETWORK
812 ClientID client_id = (ClientID)p2;
813 #endif /* ENABLE_NETWORK */
815 switch (GB(p1, 0, 16)) {
816 case 0: { // Create a new company
817 /* This command is only executed in a multiplayer game */
818 if (!_networking) return CMD_ERROR;
820 #ifdef ENABLE_NETWORK
821 /* Has the network client a correct ClientIndex? */
822 if (!(flags & DC_EXEC)) return CommandCost();
823 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
824 #ifndef DEBUG_DUMP_COMMANDS
825 /* When replaying the client ID is not a valid client; there
826 * are actually no clients at all. However, the company has to
827 * be created, otherwise we cannot rerun the game properly.
828 * So only allow a NULL client info in that case. */
829 if (ci == NULL) return CommandCost();
830 #endif /* NOT DEBUG_DUMP_COMMANDS */
832 /* Delete multiplayer progress bar */
833 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
835 Company *c = DoStartupNewCompany(false);
837 /* A new company could not be created, revert to being a spectator */
838 if (c == NULL) {
839 if (_network_server) {
840 ci->client_playas = COMPANY_SPECTATOR;
841 NetworkUpdateClientInfo(ci->client_id);
843 break;
846 /* This is the client (or non-dedicated server) who wants a new company */
847 if (client_id == _network_own_client_id) {
848 assert(_local_company == COMPANY_SPECTATOR);
849 SetLocalCompany(c->index);
850 if (!StrEmpty(_settings_client.network.default_company_pass)) {
851 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
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 #endif /* ENABLE_NETWORK */
863 break;
866 case 1: { // Make a new AI company
867 if (!(flags & DC_EXEC)) return CommandCost();
869 if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
870 Company *c = DoStartupNewCompany(true, company_id);
871 #ifdef ENABLE_NETWORK
872 if (c != NULL) NetworkServerNewCompany(c, NULL);
873 #endif /* ENABLE_NETWORK */
874 break;
877 case 2: { // Delete a company
878 CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
879 if (reason >= CRR_END) return CMD_ERROR;
881 Company *c = Company::GetIfValid(company_id);
882 if (c == NULL) return CMD_ERROR;
884 if (!(flags & DC_EXEC)) return CommandCost();
886 /* Delete any open window of the company */
887 DeleteCompanyWindows(c->index);
888 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
889 cni->FillData(c);
891 /* Show the bankrupt news */
892 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
893 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
894 SetDParamStr(2, cni->company_name);
895 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
897 /* Remove the company */
898 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
899 if (c->is_ai) AI::Stop(c->index);
901 CompanyID c_index = c->index;
902 delete c;
903 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
904 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
905 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
907 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
908 break;
911 default: return CMD_ERROR;
914 InvalidateWindowClassesData(WC_GAME_OPTIONS);
915 InvalidateWindowClassesData(WC_AI_SETTINGS);
916 InvalidateWindowClassesData(WC_AI_LIST);
918 return CommandCost();
922 * Change the company manager's face.
923 * @param tile unused
924 * @param flags operation to perform
925 * @param p1 unused
926 * @param p2 face bitmasked
927 * @param text unused
928 * @return the cost of this operation or an error
930 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
932 CompanyManagerFace cmf = (CompanyManagerFace)p2;
934 if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
936 if (flags & DC_EXEC) {
937 Company::Get(_current_company)->face = cmf;
938 MarkWholeScreenDirty();
940 return CommandCost();
944 * Change the company's company-colour
945 * @param tile unused
946 * @param flags operation to perform
947 * @param p1 bitstuffed:
948 * p1 bits 0-7 scheme to set
949 * p1 bits 8-9 set in use state or first/second colour
950 * @param p2 new colour for vehicles, property, etc.
951 * @param text unused
952 * @return the cost of this operation or an error
954 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
956 Colours colour = Extract<Colours, 0, 4>(p2);
957 LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
958 byte state = GB(p1, 8, 2);
960 if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
962 Company *c = Company::Get(_current_company);
964 /* Ensure no two companies have the same primary colour */
965 if (scheme == LS_DEFAULT && state == 0) {
966 const Company *cc;
967 FOR_ALL_COMPANIES(cc) {
968 if (cc != c && cc->colour == colour) return CMD_ERROR;
972 if (flags & DC_EXEC) {
973 switch (state) {
974 case 0:
975 c->livery[scheme].colour1 = colour;
977 /* If setting the first colour of the default scheme, adjust the
978 * original and cached company colours too. */
979 if (scheme == LS_DEFAULT) {
980 _company_colours[_current_company] = colour;
981 c->colour = colour;
982 CompanyAdminUpdate(c);
984 break;
986 case 1:
987 c->livery[scheme].colour2 = colour;
988 break;
990 case 2:
991 c->livery[scheme].in_use = colour != 0;
993 /* Now handle setting the default scheme's in_use flag.
994 * This is different to the other schemes, as it signifies if any
995 * scheme is active at all. If this flag is not set, then no
996 * processing of vehicle types occurs at all, and only the default
997 * colours will be used. */
999 /* If enabling a scheme, set the default scheme to be in use too */
1000 if (colour != 0) {
1001 c->livery[LS_DEFAULT].in_use = true;
1002 break;
1005 /* Else loop through all schemes to see if any are left enabled.
1006 * If not, disable the default scheme too. */
1007 c->livery[LS_DEFAULT].in_use = false;
1008 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1009 if (c->livery[scheme].in_use) {
1010 c->livery[LS_DEFAULT].in_use = true;
1011 break;
1014 break;
1016 default:
1017 break;
1019 ResetVehicleColourMap();
1020 MarkWholeScreenDirty();
1022 /* All graph related to companies use the company colour. */
1023 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1024 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1025 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1026 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1027 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1028 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1029 /* The smallmap owner view also stores the company colours. */
1030 BuildOwnerLegend();
1031 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1033 /* Company colour data is indirectly cached. */
1034 Vehicle *v;
1035 FOR_ALL_VEHICLES(v) {
1036 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1039 extern void UpdateObjectColours(const Company *c);
1040 UpdateObjectColours(c);
1042 return CommandCost();
1046 * Is the given name in use as name of a company?
1047 * @param name Name to search.
1048 * @return \c true if the name us unique (that is, not in use), else \c false.
1050 static bool IsUniqueCompanyName(const char *name)
1052 const Company *c;
1054 FOR_ALL_COMPANIES(c) {
1055 if (c->name != NULL && strcmp(c->name, name) == 0) return false;
1058 return true;
1062 * Change the name of the company.
1063 * @param tile unused
1064 * @param flags operation to perform
1065 * @param p1 unused
1066 * @param p2 unused
1067 * @param text the new name or an empty string when resetting to the default
1068 * @return the cost of this operation or an error
1070 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1072 bool reset = StrEmpty(text);
1074 if (!reset) {
1075 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
1076 if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1079 if (flags & DC_EXEC) {
1080 Company *c = Company::Get(_current_company);
1081 free(c->name);
1082 c->name = reset ? NULL : stredup(text);
1083 MarkWholeScreenDirty();
1084 CompanyAdminUpdate(c);
1087 return CommandCost();
1091 * Is the given name in use as president name of a company?
1092 * @param name Name to search.
1093 * @return \c true if the name us unique (that is, not in use), else \c false.
1095 static bool IsUniquePresidentName(const char *name)
1097 const Company *c;
1099 FOR_ALL_COMPANIES(c) {
1100 if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
1103 return true;
1107 * Change the name of the president.
1108 * @param tile unused
1109 * @param flags operation to perform
1110 * @param p1 unused
1111 * @param p2 unused
1112 * @param text the new name or an empty string when resetting to the default
1113 * @return the cost of this operation or an error
1115 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1117 bool reset = StrEmpty(text);
1119 if (!reset) {
1120 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
1121 if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1124 if (flags & DC_EXEC) {
1125 Company *c = Company::Get(_current_company);
1126 free(c->president_name);
1128 if (reset) {
1129 c->president_name = NULL;
1130 } else {
1131 c->president_name = stredup(text);
1133 if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
1134 char buf[80];
1136 seprintf(buf, lastof(buf), "%s Transport", text);
1137 DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
1141 MarkWholeScreenDirty();
1142 CompanyAdminUpdate(c);
1145 return CommandCost();
1149 * Get the service interval for the given company and vehicle type.
1150 * @param c The company, or NULL for client-default settings.
1151 * @param type The vehicle type to get the interval for.
1152 * @return The service interval.
1154 int CompanyServiceInterval(const Company *c, VehicleType type)
1156 const VehicleDefaultSettings *vds = (c == NULL) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1157 switch (type) {
1158 default: NOT_REACHED();
1159 case VEH_TRAIN: return vds->servint_trains;
1160 case VEH_ROAD: return vds->servint_roadveh;
1161 case VEH_AIRCRAFT: return vds->servint_aircraft;
1162 case VEH_SHIP: return vds->servint_ships;