Add support for deleted functions
[openttd/fttd.git] / src / company_cmd.cpp
blobdec2d083a4d23803423df0253f7af5e1c98a1122
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 "map/common.h"
41 #include "table/strings.h"
43 CompanyByte _local_company; ///< Company controlled by the human player at this client. Can also be #COMPANY_SPECTATOR.
44 CompanyByte _current_company; ///< Company currently doing an action.
45 Colours _company_colours[MAX_COMPANIES]; ///< NOSAVE: can be determined from company structs.
46 CompanyManagerFace _company_manager_face; ///< for company manager face storage in openttd.cfg
47 uint _next_competitor_start; ///< the number of ticks before the next AI is started
48 uint _cur_company_tick_index; ///< used to generate a name for one company that doesn't have a name yet per tick
50 CompanyPool _company_pool("Company"); ///< Pool of companies.
51 INSTANTIATE_POOL_METHODS(Company)
53 /**
54 * Constructor.
55 * @param name_1 Name of the company.
56 * @param is_ai A computer program is running for this company.
58 Company::Company(uint16 name_1, bool is_ai)
60 this->name_1 = name_1;
61 this->location_of_HQ = INVALID_TILE;
62 this->is_ai = is_ai;
63 this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
64 this->clear_limit = _settings_game.construction.clear_frame_burst << 16;
65 this->tree_limit = _settings_game.construction.tree_frame_burst << 16;
67 for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
68 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
71 /** Destructor. */
72 Company::~Company()
74 if (CleaningPool()) return;
76 DeleteCompanyWindows(this->index);
79 /**
80 * Invalidating some stuff after removing item from the pool.
81 * @param index index of deleted item
83 void Company::PostDestructor(size_t index)
85 InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
86 InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
87 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
88 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
89 /* If the currently shown error message has this company in it, then close it. */
90 InvalidateWindowData(WC_ERRMSG, 0);
93 /**
94 * Sets the local company and updates the settings that are set on a
95 * per-company basis to reflect the core's state in the GUI.
96 * @param new_company the new company
97 * @pre Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE
99 void SetLocalCompany(CompanyID new_company)
101 /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
102 assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
104 #ifdef ENABLE_NETWORK
105 /* Delete the chat window, if you were team chatting. */
106 InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
107 #endif
109 assert(IsLocalCompany());
111 _current_company = _local_company = new_company;
113 /* Delete any construction windows... */
114 DeleteConstructionWindows();
116 /* ... and redraw the whole screen. */
117 MarkWholeScreenDirty();
118 InvalidateWindowClassesData(WC_SIGN_LIST, -1);
122 * Get the colour for DrawString-subroutines which matches the colour of the company.
123 * @param company Company to get the colour of.
124 * @return Colour of \a company.
126 TextColour GetDrawStringCompanyColour(CompanyID company)
128 if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
129 return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
133 * Draw the icon of a company.
134 * @param c Company that needs its icon drawn.
135 * @param x Horizontal coordinate of the icon.
136 * @param y Vertical coordinate of the icon.
138 void DrawCompanyIcon(CompanyID c, int x, int y)
140 DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
144 * Checks whether a company manager's face is a valid encoding.
145 * Unused bits are not enforced to be 0.
146 * @param cmf the fact to check
147 * @return true if and only if the face is valid
149 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
151 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
153 GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
154 bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
155 bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
156 bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
158 if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
159 for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
160 switch (cmfv) {
161 case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
162 case CMFV_LIPS: // FALL THROUGH
163 case CMFV_NOSE: if (has_moustache) continue; break;
164 case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
165 case CMFV_GLASSES: if (!has_glasses) continue; break;
166 default: break;
168 if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
171 return true;
175 * Refresh all windows owned by a company.
176 * @param company Company that changed, and needs its windows refreshed.
178 void InvalidateCompanyWindows(const Company *company)
180 CompanyID cid = company->index;
182 if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
183 SetWindowDirty(WC_FINANCES, cid);
187 * Verify whether the company can pay the bill.
188 * @param cost [inout] Money to pay, is changed to an error if the company does not have enough money.
189 * @return Function returns \c true if the company has enough money, else it returns \c false.
191 bool CheckCompanyHasMoney(CommandCost &cost)
193 if (cost.GetCost() > 0) {
194 const Company *c = Company::GetIfValid(_current_company);
195 if (c != NULL && cost.GetCost() > c->money) {
196 SetDParam(0, cost.GetCost());
197 cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
198 return false;
201 return true;
205 * Deduct costs of a command from the money of a company.
206 * @param c Company to pay the bill.
207 * @param cost Money to pay.
209 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
211 if (cost.GetCost() == 0) return;
212 assert(cost.GetExpensesType() != INVALID_EXPENSES);
214 c->money -= cost.GetCost();
215 c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
217 if (HasBit(1 << EXPENSES_TRAIN_INC |
218 1 << EXPENSES_ROADVEH_INC |
219 1 << EXPENSES_AIRCRAFT_INC |
220 1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
221 c->cur_economy.income -= cost.GetCost();
222 } else if (HasBit(1 << EXPENSES_TRAIN_RUN |
223 1 << EXPENSES_ROADVEH_RUN |
224 1 << EXPENSES_AIRCRAFT_RUN |
225 1 << EXPENSES_SHIP_RUN |
226 1 << EXPENSES_PROPERTY |
227 1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
228 c->cur_economy.expenses -= cost.GetCost();
231 InvalidateCompanyWindows(c);
235 * Subtract money from the #_current_company, if the company is valid.
236 * @param cost Money to pay.
238 void SubtractMoneyFromCompany(CommandCost cost)
240 Company *c = Company::GetIfValid(_current_company);
241 if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
245 * Subtract money from a company, including the money fraction.
246 * @param company Company paying the bill.
247 * @param cst Cost of a command.
249 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
251 Company *c = Company::Get(company);
252 byte m = c->money_fraction;
253 Money cost = cst.GetCost();
255 c->money_fraction = m - (byte)cost;
256 cost >>= 8;
257 if (c->money_fraction > m) cost++;
258 if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
261 /** Update the landscaping limits per company. */
262 void UpdateLandscapingLimits()
264 Company *c;
265 FOR_ALL_COMPANIES(c) {
266 c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
267 c->clear_limit = min(c->clear_limit + _settings_game.construction.clear_per_64k_frames, (uint32)_settings_game.construction.clear_frame_burst << 16);
268 c->tree_limit = min(c->tree_limit + _settings_game.construction.tree_per_64k_frames, (uint32)_settings_game.construction.tree_frame_burst << 16);
273 * Set the right DParams to get the name of an owner.
274 * @param owner the owner to get the name of.
275 * @param tile optional tile to get the right town.
276 * @pre if tile == 0, then owner can't be OWNER_TOWN.
278 void GetNameOfOwner(Owner owner, TileIndex tile)
280 SetDParam(2, owner);
282 if (owner != OWNER_TOWN) {
283 if (!Company::IsValidID(owner)) {
284 SetDParam(0, STR_COMPANY_SOMEONE);
285 } else {
286 SetDParam(0, STR_COMPANY_NAME);
287 SetDParam(1, owner);
289 } else {
290 assert(tile != 0);
291 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
293 SetDParam(0, STR_TOWN_NAME);
294 SetDParam(1, t->index);
300 * Check whether the current owner owns something.
301 * If that isn't the case an appropriate error will be given.
302 * @param owner the owner of the thing to check.
303 * @param tile optional tile to get the right town.
304 * @pre if tile == 0 then the owner can't be OWNER_TOWN.
305 * @return A succeeded command iff it's owned by the current company, else a failed command.
307 CommandCost CheckOwnership(Owner owner, TileIndex tile)
309 assert(owner < OWNER_END);
310 assert(owner != OWNER_TOWN || tile != 0);
312 if (owner == _current_company) return CommandCost();
314 GetNameOfOwner(owner, tile);
315 return_cmd_error(STR_ERROR_OWNED_BY);
319 * Check whether the current owner owns the stuff on
320 * the given tile. If that isn't the case an
321 * appropriate error will be given.
322 * @param tile the tile to check.
323 * @return A succeeded command iff it's owned by the current company, else a failed command.
325 CommandCost CheckTileOwnership(TileIndex tile)
327 Owner owner = GetTileOwner(tile);
329 assert(owner < OWNER_END);
331 if (owner == _current_company) return CommandCost();
333 /* no need to get the name of the owner unless we're the local company (saves some time) */
334 if (IsLocalCompany()) GetNameOfOwner(owner, tile);
335 return_cmd_error(STR_ERROR_OWNED_BY);
339 * Generate the name of a company from the last build coordinate.
340 * @param c Company to give a name.
342 static void GenerateCompanyName(Company *c)
344 /* Reserve space for extra unicode character. We need to do this to be able
345 * to detect too long company name. */
346 char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
348 if (c->name_1 != STR_SV_UNNAMED) return;
349 if (c->last_build_coordinate == 0) return;
351 Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
353 StringID str;
354 uint32 strp;
355 if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
356 str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
357 strp = t->townnameparts;
359 verify_name:;
360 /* No companies must have this name already */
361 Company *cc;
362 FOR_ALL_COMPANIES(cc) {
363 if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
366 GetString(buffer, str, lastof(buffer));
367 if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
369 set_name:;
370 c->name_1 = str;
371 c->name_2 = strp;
373 MarkWholeScreenDirty();
375 if (c->is_ai) {
376 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
377 cni->FillData(c);
378 SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
379 SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
380 SetDParamStr(2, cni->company_name);
381 SetDParam(3, t->index);
382 AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NT_COMPANY_INFO, NF_COMPANY, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
384 return;
386 bad_town_name:;
388 if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
389 str = SPECSTR_ANDCO_NAME;
390 strp = c->president_name_2;
391 goto set_name;
392 } else {
393 str = SPECSTR_ANDCO_NAME;
394 strp = Random();
395 goto verify_name;
399 /** Sorting weights for the company colours. */
400 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
401 /** Similar colours, so we can try to prevent same coloured companies. */
402 static const Colours _similar_colour[COLOUR_END][2] = {
403 { COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
404 { COLOUR_GREEN, COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
405 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_PINK
406 { COLOUR_ORANGE, INVALID_COLOUR }, // COLOUR_YELLOW
407 { INVALID_COLOUR, INVALID_COLOUR }, // COLOUR_RED
408 { COLOUR_DARK_BLUE, COLOUR_BLUE }, // COLOUR_LIGHT_BLUE
409 { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
410 { COLOUR_PALE_GREEN, COLOUR_GREEN }, // COLOUR_DARK_GREEN
411 { COLOUR_DARK_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
412 { COLOUR_BROWN, COLOUR_ORANGE }, // COLOUR_CREAM
413 { COLOUR_PURPLE, INVALID_COLOUR }, // COLOUR_MAUVE
414 { COLOUR_MAUVE, INVALID_COLOUR }, // COLOUR_PURPLE
415 { COLOUR_YELLOW, COLOUR_CREAM }, // COLOUR_ORANGE
416 { COLOUR_CREAM, INVALID_COLOUR }, // COLOUR_BROWN
417 { COLOUR_WHITE, INVALID_COLOUR }, // COLOUR_GREY
418 { COLOUR_GREY, INVALID_COLOUR }, // COLOUR_WHITE
422 * Generate a company colour.
423 * @return Generated company colour.
425 static Colours GenerateCompanyColour()
427 Colours colours[COLOUR_END];
429 /* Initialize array */
430 for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
432 /* And randomize it */
433 for (uint i = 0; i < 100; i++) {
434 uint r = Random();
435 Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
438 /* Bubble sort it according to the values in table 1 */
439 for (uint i = 0; i < COLOUR_END; i++) {
440 for (uint j = 1; j < COLOUR_END; j++) {
441 if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
442 Swap(colours[j - 1], colours[j]);
447 /* Move the colours that look similar to each company's colour to the side */
448 Company *c;
449 FOR_ALL_COMPANIES(c) {
450 Colours pcolour = (Colours)c->colour;
452 for (uint i = 0; i < COLOUR_END; i++) {
453 if (colours[i] == pcolour) {
454 colours[i] = INVALID_COLOUR;
455 break;
459 for (uint j = 0; j < 2; j++) {
460 Colours similar = _similar_colour[pcolour][j];
461 if (similar == INVALID_COLOUR) break;
463 for (uint i = 1; i < COLOUR_END; i++) {
464 if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
469 /* Return the first available colour */
470 for (uint i = 0; i < COLOUR_END; i++) {
471 if (colours[i] != INVALID_COLOUR) return colours[i];
474 NOT_REACHED();
478 * Generate a random president name of a company.
479 * @param c Company that needs a new president name.
481 static void GeneratePresidentName(Company *c)
483 for (;;) {
484 restart:;
485 c->president_name_2 = Random();
486 c->president_name_1 = SPECSTR_PRESIDENT_NAME;
488 /* Reserve space for extra unicode character. We need to do this to be able
489 * to detect too long president name. */
490 char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
491 SetDParam(0, c->index);
492 GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
493 if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
495 Company *cc;
496 FOR_ALL_COMPANIES(cc) {
497 if (c != cc) {
498 /* Reserve extra space so even overlength president names can be compared. */
499 char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
500 SetDParam(0, cc->index);
501 GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
502 if (strcmp(buffer2, buffer) == 0) goto restart;
505 return;
510 * Reset the livery schemes to the company's primary colour.
511 * This is used on loading games without livery information and on new company start up.
512 * @param c Company to reset.
514 void ResetCompanyLivery(Company *c)
516 for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
517 c->livery[scheme].in_use = false;
518 c->livery[scheme].colour1 = c->colour;
519 c->livery[scheme].colour2 = c->colour;
524 * Create a new company and sets all company variables default values
526 * @param is_ai is an AI company?
527 * @param company CompanyID to use for the new company
528 * @return the company struct
530 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
532 if (!Company::CanAllocateItem()) return NULL;
534 /* we have to generate colour before this company is valid */
535 Colours colour = GenerateCompanyColour();
537 Company *c;
538 if (company == INVALID_COMPANY) {
539 c = new Company(STR_SV_UNNAMED, is_ai);
540 } else {
541 if (Company::IsValidID(company)) return NULL;
542 c = new (company) Company(STR_SV_UNNAMED, is_ai);
545 c->colour = colour;
547 ResetCompanyLivery(c);
548 _company_colours[c->index] = (Colours)c->colour;
550 c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
552 c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
554 c->avail_railtypes = GetCompanyRailtypes(c->index);
555 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
556 c->inaugurated_year = _cur_year;
557 RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false, false); // create a random company manager face
559 SetDefaultCompanySettings(c->index);
561 GeneratePresidentName(c);
563 SetWindowDirty(WC_GRAPH_LEGEND, 0);
564 SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
565 SetWindowDirty(WC_CLIENT_LIST, 0);
566 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
567 BuildOwnerLegend();
568 InvalidateWindowData(WC_SMALLMAP, 0, 1);
570 if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
572 AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
573 Game::NewEvent(new ScriptEventCompanyNew(c->index));
575 return c;
578 /** Start the next competitor now. */
579 void StartupCompanies()
581 _next_competitor_start = 0;
584 /** Start a new competitor company if possible. */
585 static void MaybeStartNewCompany()
587 #ifdef ENABLE_NETWORK
588 if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
589 #endif /* ENABLE_NETWORK */
591 Company *c;
593 /* count number of competitors */
594 uint n = 0;
595 FOR_ALL_COMPANIES(c) {
596 if (c->is_ai) n++;
599 if (n < (uint)_settings_game.difficulty.max_no_competitors) {
600 /* Send a command to all clients to start up a new AI.
601 * Works fine for Multiplayer and Singleplayer */
602 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
606 /** Initialize the pool of companies. */
607 void InitializeCompanies()
609 _cur_company_tick_index = 0;
613 * May company \a cbig buy company \a csmall?
614 * @param cbig Company buying \a csmall.
615 * @param csmall Company getting bought.
616 * @return Return \c true if it is allowed.
618 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
620 const Company *c1 = Company::Get(cbig);
621 const Company *c2 = Company::Get(csmall);
623 /* Do the combined vehicle counts stay within the limits? */
624 return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
625 c1->group_all[VEH_ROAD].num_vehicle + c2->group_all[VEH_ROAD].num_vehicle <= _settings_game.vehicle.max_roadveh &&
626 c1->group_all[VEH_SHIP].num_vehicle + c2->group_all[VEH_SHIP].num_vehicle <= _settings_game.vehicle.max_ships &&
627 c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
631 * Handle the bankruptcy take over of a company.
632 * Companies going bankrupt will ask the other companies in order of their
633 * performance rating, so better performing companies get the 'do you want to
634 * merge with Y' question earlier. The question will then stay till either the
635 * company has gone bankrupt or got merged with a company.
637 * @param c the company that is going bankrupt.
639 static void HandleBankruptcyTakeover(Company *c)
641 /* Amount of time out for each company to take over a company;
642 * Timeout is a quarter (3 months of 30 days) divided over the
643 * number of companies. The minimum number of days in a quarter
644 * is 90: 31 in January, 28 in February and 31 in March.
645 * Note that the company going bankrupt can't buy itself. */
646 static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
648 assert(c->bankrupt_asked != 0);
650 /* We're currently asking some company to buy 'us' */
651 if (c->bankrupt_timeout != 0) {
652 c->bankrupt_timeout -= MAX_COMPANIES;
653 if (c->bankrupt_timeout > 0) return;
654 c->bankrupt_timeout = 0;
656 return;
659 /* Did we ask everyone for bankruptcy? If so, bail out. */
660 if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
662 Company *c2, *best = NULL;
663 int32 best_performance = -1;
665 /* Ask the company with the highest performance history first */
666 FOR_ALL_COMPANIES(c2) {
667 if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
668 !HasBit(c->bankrupt_asked, c2->index) &&
669 best_performance < c2->old_economy[1].performance_history &&
670 MayCompanyTakeOver(c2->index, c->index)) {
671 best_performance = c2->old_economy[1].performance_history;
672 best = c2;
676 /* Asked all companies? */
677 if (best_performance == -1) {
678 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
679 return;
682 SetBit(c->bankrupt_asked, best->index);
684 c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
685 if (best->is_ai) {
686 AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
687 } else if (IsInteractiveCompany(best->index)) {
688 ShowBuyCompanyDialog(c->index);
692 /** Called every tick for updating some company info. */
693 void OnTick_Companies()
695 if (_game_mode == GM_EDITOR) return;
697 Company *c = Company::GetIfValid(_cur_company_tick_index);
698 if (c != NULL) {
699 if (c->name_1 != 0) GenerateCompanyName(c);
700 if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
703 if (_next_competitor_start == 0) {
704 _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
707 if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
708 MaybeStartNewCompany();
711 _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
715 * A year has passed, update the economic data of all companies, and perhaps show the
716 * financial overview window of the local company.
718 void CompaniesYearlyLoop()
720 Company *c;
722 /* Copy statistics */
723 FOR_ALL_COMPANIES(c) {
724 memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
725 memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
726 SetWindowDirty(WC_FINANCES, c->index);
729 if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
730 ShowCompanyFinances(_local_company);
731 c = Company::Get(_local_company);
732 if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
733 if (_settings_client.sound.new_year) SndPlayFx(SND_01_BAD_YEAR);
734 } else {
735 if (_settings_client.sound.new_year) SndPlayFx(SND_00_GOOD_YEAR);
741 * Fill the CompanyNewsInformation struct with the required data.
742 * @param c the current company.
743 * @param other the other company (use \c NULL if not relevant).
745 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
747 SetDParam(0, c->index);
748 GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
750 if (other == NULL) {
751 *this->other_company_name = '\0';
752 } else {
753 SetDParam(0, other->index);
754 GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
755 c = other;
758 SetDParam(0, c->index);
759 GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
761 this->colour = c->colour;
762 this->face = c->face;
767 * Called whenever company related information changes in order to notify admins.
768 * @param company The company data changed of.
770 void CompanyAdminUpdate(const Company *company)
772 #ifdef ENABLE_NETWORK
773 if (_network_server) NetworkAdminCompanyUpdate(company);
774 #endif /* ENABLE_NETWORK */
778 * Called whenever a company is removed in order to notify admins.
779 * @param company_id The company that was removed.
780 * @param reason The reason the company was removed.
782 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
784 #ifdef ENABLE_NETWORK
785 if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
786 #endif /* ENABLE_NETWORK */
790 * Control the companies: add, delete, etc.
791 * @param tile unused
792 * @param flags operation to perform
793 * @param p1 various functionality
794 * - bits 0..15:
795 * = 0 - create a new company
796 * = 1 - create a new AI company
797 * = 2 - delete a company
798 * - bits 16..24: CompanyID
799 * @param p2 ClientID
800 * @param text unused
801 * @return the cost of this operation or an error
803 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
805 InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
806 CompanyID company_id = (CompanyID)GB(p1, 16, 8);
807 #ifdef ENABLE_NETWORK
808 ClientID client_id = (ClientID)p2;
809 #endif /* ENABLE_NETWORK */
811 switch (GB(p1, 0, 16)) {
812 case 0: { // Create a new company
813 /* This command is only executed in a multiplayer game */
814 if (!_networking) return CMD_ERROR;
816 #ifdef ENABLE_NETWORK
817 /* Has the network client a correct ClientIndex? */
818 if (!(flags & DC_EXEC)) return CommandCost();
819 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
820 #ifndef DEBUG_DUMP_COMMANDS
821 /* When replaying the client ID is not a valid client; there
822 * are actually no clients at all. However, the company has to
823 * be created, otherwise we cannot rerun the game properly.
824 * So only allow a NULL client info in that case. */
825 if (ci == NULL) return CommandCost();
826 #endif /* NOT DEBUG_DUMP_COMMANDS */
828 /* Delete multiplayer progress bar */
829 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
831 Company *c = DoStartupNewCompany(false);
833 /* A new company could not be created, revert to being a spectator */
834 if (c == NULL) {
835 if (_network_server) {
836 ci->client_playas = COMPANY_SPECTATOR;
837 NetworkUpdateClientInfo(ci->client_id);
839 break;
842 /* This is the client (or non-dedicated server) who wants a new company */
843 if (client_id == _network_own_client_id) {
844 assert(_local_company == COMPANY_SPECTATOR);
845 SetLocalCompany(c->index);
846 if (!StrEmpty(_settings_client.network.default_company_pass)) {
847 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
850 /* Now that we have a new company, broadcast our company settings to
851 * all clients so everything is in sync */
852 SyncCompanySettings();
854 MarkWholeScreenDirty();
857 if (_network_server) {
858 if (ci != NULL) {
859 /* ci is only NULL when replaying.
860 * When replaying no client is actually in need of an update. */
861 ci->client_playas = c->index;
862 NetworkUpdateClientInfo(ci->client_id);
865 if (Company::IsValidID(c->index)) {
866 _network_company_states[c->index].months_empty = 0;
867 _network_company_states[c->index].password[0] = '\0';
868 NetworkServerUpdateCompanyPassworded(c->index, false);
870 /* XXX - When a client joins, we automatically set its name to the
871 * client's name (for some reason). As it stands now only the server
872 * knows the client's name, so it needs to send out a "broadcast" to
873 * do this. To achieve this we send a network command. However, it
874 * uses _local_company to execute the command as. To prevent abuse
875 * (eg. only yourself can change your name/company), we 'cheat' by
876 * impersonation _local_company as the server. Not the best solution;
877 * but it works.
878 * TODO: Perhaps this could be improved by when the client is ready
879 * with joining to let it send itself the command, and not the server?
880 * For example in network_client.c:534? */
881 if (ci != NULL) {
882 /* ci is only NULL when replaying.
883 * When replaying, the command to rename the president will
884 * automatically be ran, so this is not even needed to get
885 * the exact same state. */
886 NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, c->index);
890 /* Announce new company on network. */
891 NetworkAdminCompanyInfo(c, true);
893 if (ci != NULL) {
894 /* ci is only NULL when replaying.
895 * When replaying, the message that someone started a new company
896 * is not interesting at all. */
897 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
900 #endif /* ENABLE_NETWORK */
901 break;
904 case 1: // Make a new AI company
905 if (!(flags & DC_EXEC)) return CommandCost();
907 if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
908 DoStartupNewCompany(true, company_id);
909 break;
911 case 2: { // Delete a company
912 CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
913 if (reason >= CRR_END) return CMD_ERROR;
915 Company *c = Company::GetIfValid(company_id);
916 if (c == NULL) return CMD_ERROR;
918 if (!(flags & DC_EXEC)) return CommandCost();
920 /* Delete any open window of the company */
921 DeleteCompanyWindows(c->index);
922 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
923 cni->FillData(c);
925 /* Show the bankrupt news */
926 SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
927 SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
928 SetDParamStr(2, cni->company_name);
929 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
931 /* Remove the company */
932 ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
933 if (c->is_ai) AI::Stop(c->index);
935 CompanyID c_index = c->index;
936 delete c;
937 AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
938 Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
939 CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
941 if (StoryPage::GetNumItems() == 0 || Goal::GetNumItems() == 0) InvalidateWindowData(WC_MAIN_TOOLBAR, 0);
942 break;
945 default: return CMD_ERROR;
948 InvalidateWindowClassesData(WC_GAME_OPTIONS);
949 InvalidateWindowClassesData(WC_AI_SETTINGS);
950 InvalidateWindowClassesData(WC_AI_LIST);
952 return CommandCost();
956 * Change the company manager's face.
957 * @param tile unused
958 * @param flags operation to perform
959 * @param p1 unused
960 * @param p2 face bitmasked
961 * @param text unused
962 * @return the cost of this operation or an error
964 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
966 CompanyManagerFace cmf = (CompanyManagerFace)p2;
968 if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
970 if (flags & DC_EXEC) {
971 Company::Get(_current_company)->face = cmf;
972 MarkWholeScreenDirty();
974 return CommandCost();
978 * Change the company's company-colour
979 * @param tile unused
980 * @param flags operation to perform
981 * @param p1 bitstuffed:
982 * p1 bits 0-7 scheme to set
983 * p1 bits 8-9 set in use state or first/second colour
984 * @param p2 new colour for vehicles, property, etc.
985 * @param text unused
986 * @return the cost of this operation or an error
988 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
990 Colours colour = Extract<Colours, 0, 4>(p2);
991 LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
992 byte state = GB(p1, 8, 2);
994 if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
996 Company *c = Company::Get(_current_company);
998 /* Ensure no two companies have the same primary colour */
999 if (scheme == LS_DEFAULT && state == 0) {
1000 const Company *cc;
1001 FOR_ALL_COMPANIES(cc) {
1002 if (cc != c && cc->colour == colour) return CMD_ERROR;
1006 if (flags & DC_EXEC) {
1007 switch (state) {
1008 case 0:
1009 c->livery[scheme].colour1 = colour;
1011 /* If setting the first colour of the default scheme, adjust the
1012 * original and cached company colours too. */
1013 if (scheme == LS_DEFAULT) {
1014 _company_colours[_current_company] = colour;
1015 c->colour = colour;
1016 CompanyAdminUpdate(c);
1018 break;
1020 case 1:
1021 c->livery[scheme].colour2 = colour;
1022 break;
1024 case 2:
1025 c->livery[scheme].in_use = colour != 0;
1027 /* Now handle setting the default scheme's in_use flag.
1028 * This is different to the other schemes, as it signifies if any
1029 * scheme is active at all. If this flag is not set, then no
1030 * processing of vehicle types occurs at all, and only the default
1031 * colours will be used. */
1033 /* If enabling a scheme, set the default scheme to be in use too */
1034 if (colour != 0) {
1035 c->livery[LS_DEFAULT].in_use = true;
1036 break;
1039 /* Else loop through all schemes to see if any are left enabled.
1040 * If not, disable the default scheme too. */
1041 c->livery[LS_DEFAULT].in_use = false;
1042 for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
1043 if (c->livery[scheme].in_use) {
1044 c->livery[LS_DEFAULT].in_use = true;
1045 break;
1048 break;
1050 default:
1051 break;
1053 ResetVehicleColourMap();
1054 MarkWholeScreenDirty();
1056 /* All graph related to companies use the company colour. */
1057 InvalidateWindowData(WC_INCOME_GRAPH, 0);
1058 InvalidateWindowData(WC_OPERATING_PROFIT, 0);
1059 InvalidateWindowData(WC_DELIVERED_CARGO, 0);
1060 InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
1061 InvalidateWindowData(WC_COMPANY_VALUE, 0);
1062 InvalidateWindowData(WC_LINKGRAPH_LEGEND, 0);
1063 /* The smallmap owner view also stores the company colours. */
1064 BuildOwnerLegend();
1065 InvalidateWindowData(WC_SMALLMAP, 0, 1);
1067 /* Company colour data is indirectly cached. */
1068 Vehicle *v;
1069 FOR_ALL_VEHICLES(v) {
1070 if (v->owner == _current_company) v->InvalidateNewGRFCache();
1073 extern void UpdateObjectColours(const Company *c);
1074 UpdateObjectColours(c);
1076 return CommandCost();
1080 * Is the given name in use as name of a company?
1081 * @param name Name to search.
1082 * @return \c true if the name us unique (that is, not in use), else \c false.
1084 static bool IsUniqueCompanyName(const char *name)
1086 const Company *c;
1088 FOR_ALL_COMPANIES(c) {
1089 if (c->name != NULL && strcmp(c->name, name) == 0) return false;
1092 return true;
1096 * Change the name of the company.
1097 * @param tile unused
1098 * @param flags operation to perform
1099 * @param p1 unused
1100 * @param p2 unused
1101 * @param text the new name or an empty string when resetting to the default
1102 * @return the cost of this operation or an error
1104 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1106 bool reset = StrEmpty(text);
1108 if (!reset) {
1109 if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
1110 if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1113 if (flags & DC_EXEC) {
1114 Company *c = Company::Get(_current_company);
1115 free(c->name);
1116 c->name = reset ? NULL : strdup(text);
1117 MarkWholeScreenDirty();
1118 CompanyAdminUpdate(c);
1121 return CommandCost();
1125 * Is the given name in use as president name of a company?
1126 * @param name Name to search.
1127 * @return \c true if the name us unique (that is, not in use), else \c false.
1129 static bool IsUniquePresidentName(const char *name)
1131 const Company *c;
1133 FOR_ALL_COMPANIES(c) {
1134 if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
1137 return true;
1141 * Change the name of the president.
1142 * @param tile unused
1143 * @param flags operation to perform
1144 * @param p1 unused
1145 * @param p2 unused
1146 * @param text the new name or an empty string when resetting to the default
1147 * @return the cost of this operation or an error
1149 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1151 bool reset = StrEmpty(text);
1153 if (!reset) {
1154 if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
1155 if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
1158 if (flags & DC_EXEC) {
1159 Company *c = Company::Get(_current_company);
1160 free(c->president_name);
1162 if (reset) {
1163 c->president_name = NULL;
1164 } else {
1165 c->president_name = strdup(text);
1167 if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
1168 char buf[80];
1170 snprintf(buf, lengthof(buf), "%s Transport", text);
1171 DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
1175 MarkWholeScreenDirty();
1176 CompanyAdminUpdate(c);
1179 return CommandCost();
1183 * Get the service interval for the given company and vehicle type.
1184 * @param c The company, or NULL for client-default settings.
1185 * @param type The vehicle type to get the interval for.
1186 * @return The service interval.
1188 int CompanyServiceInterval(const Company *c, VehicleType type)
1190 const VehicleDefaultSettings *vds = (c == NULL) ? &_settings_client.company.vehicle : &c->settings.vehicle;
1191 switch (type) {
1192 default: NOT_REACHED();
1193 case VEH_TRAIN: return vds->servint_trains;
1194 case VEH_ROAD: return vds->servint_roadveh;
1195 case VEH_AIRCRAFT: return vds->servint_aircraft;
1196 case VEH_SHIP: return vds->servint_ships;