# company_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id: company_cmd.cpp 19665 2010-04-17 22:27:49Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "engine_base.h"
    00014 #include "company_func.h"
    00015 #include "company_gui.h"
    00016 #include "town.h"
    00017 #include "news_func.h"
    00018 #include "cmd_helper.h"
    00019 #include "command_func.h"
    00020 #include "network/network.h"
    00021 #include "network/network_func.h"
    00022 #include "network/network_base.h"
    00023 #include "ai/ai.hpp"
    00024 #include "company_manager_face.h"
    00025 #include "group.h"
    00026 #include "window_func.h"
    00027 #include "strings_func.h"
    00028 #include "gfx_func.h"
    00029 #include "date_func.h"
    00030 #include "sound_func.h"
    00031 #include "autoreplace_func.h"
    00032 #include "autoreplace_gui.h"
    00033 #include "rail.h"
    00034 #include "core/pool_func.hpp"
    00035 #include "settings_func.h"
    00036 #include "vehicle_base.h"
    00037 #include "vehicle_func.h"
    00038 #include "sprite.h"
    00039
    00040 #include "table/strings.h"
    00041
    00042 CompanyByte _local_company;
    00043 CompanyByte _current_company;
    00044 /* NOSAVE: can be determined from company structs */
    00045 Colours _company_colours[MAX_COMPANIES];
    00046 CompanyManagerFace _company_manager_face;
    00047 uint _next_competitor_start;
    00048 uint _cur_company_tick_index;
    00049
    00050 CompanyPool _company_pool("Company");
    00051 INSTANTIATE_POOL_METHODS(Company)
    00052
    00053 Company::Company(uint16 name_1, bool is_ai) :
    00054   name_1(name_1),
    00055   location_of_HQ(INVALID_TILE),
    00056   is_ai(is_ai)
    00057 {
    00058   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
    00059   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
    00060 }
    00061
    00062 Company::~Company()
    00063 {
    00064   free(this->name);
    00065   free(this->president_name);
    00066   free(this->num_engines);
    00067
    00068   if (CleaningPool()) return;
    00069
    00070   DeleteCompanyWindows(this->index);
    00071 }
    00072
    00077 void Company::PostDestructor(size_t index)
    00078 {
    00079   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
    00080   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
    00081   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00082   /* If the currently shown error message has this company in it, the close it. */
    00083   InvalidateWindowData(WC_ERRMSG, 0);
    00084 }
    00085
    00092 void SetLocalCompany(CompanyID new_company)
    00093 {
    00094   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
    00095   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
    00096
    00097 #ifdef ENABLE_NETWORK
    00098   /* Delete the chat window, if you were team chatting. */
    00099   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
    00100 #endif
    00101
    00102   _local_company = new_company;
    00103
    00104   /* Delete any construction windows... */
    00105   DeleteConstructionWindows();
    00106
    00107   /* ... and redraw the whole screen. */
    00108   MarkWholeScreenDirty();
    00109 }
    00110
    00111 uint16 GetDrawStringCompanyColour(CompanyID company)
    00112 {
    00113   /* Get the colour for DrawString-subroutines which matches the colour
    00114    * of the company */
    00115   if (!Company::IsValidID(company)) return _colour_gradient[COLOUR_WHITE][4] | IS_PALETTE_COLOUR;
    00116   return (_colour_gradient[_company_colours[company]][4]) | IS_PALETTE_COLOUR;
    00117 }
    00118
    00119 void DrawCompanyIcon(CompanyID c, int x, int y)
    00120 {
    00121   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
    00122 }
    00123
    00130 bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
    00131 {
    00132   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
    00133
    00134   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
    00135   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
    00136   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
    00137   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
    00138
    00139   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
    00140   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
    00141     switch (cmfv) {
    00142       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
    00143       case CMFV_LIPS:        // FALL THROUGH
    00144       case CMFV_NOSE:        if (has_moustache)    continue; break;
    00145       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
    00146       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
    00147       default: break;
    00148     }
    00149     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
    00150   }
    00151
    00152   return true;
    00153 }
    00154
    00155 void InvalidateCompanyWindows(const Company *company)
    00156 {
    00157   CompanyID cid = company->index;
    00158
    00159   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
    00160   SetWindowDirty(WC_FINANCES, cid);
    00161 }
    00162
    00163 bool CheckCompanyHasMoney(CommandCost &cost)
    00164 {
    00165   if (cost.GetCost() > 0) {
    00166     const Company *c = Company::GetIfValid(_current_company);
    00167     if (c != NULL && cost.GetCost() > c->money) {
    00168       SetDParam(0, cost.GetCost());
    00169       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
    00170       return false;
    00171     }
    00172   }
    00173   return true;
    00174 }
    00175
    00176 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
    00177 {
    00178   if (cost.GetCost() == 0) return;
    00179   assert(cost.GetExpensesType() != INVALID_EXPENSES);
    00180
    00181   c->money -= cost.GetCost();
    00182   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
    00183
    00184   if (HasBit(1 << EXPENSES_TRAIN_INC    |
    00185              1 << EXPENSES_ROADVEH_INC  |
    00186              1 << EXPENSES_AIRCRAFT_INC |
    00187              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
    00188     c->cur_economy.income -= cost.GetCost();
    00189   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
    00190                     1 << EXPENSES_ROADVEH_RUN  |
    00191                     1 << EXPENSES_AIRCRAFT_RUN |
    00192                     1 << EXPENSES_SHIP_RUN     |
    00193                     1 << EXPENSES_PROPERTY     |
    00194                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
    00195     c->cur_economy.expenses -= cost.GetCost();
    00196   }
    00197
    00198   InvalidateCompanyWindows(c);
    00199 }
    00200
    00201 void SubtractMoneyFromCompany(CommandCost cost)
    00202 {
    00203   Company *c = Company::GetIfValid(_current_company);
    00204   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
    00205 }
    00206
    00207 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
    00208 {
    00209   Company *c = Company::Get(company);
    00210   byte m = c->money_fraction;
    00211   Money cost = cst.GetCost();
    00212
    00213   c->money_fraction = m - (byte)cost;
    00214   cost >>= 8;
    00215   if (c->money_fraction > m) cost++;
    00216   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
    00217 }
    00218
    00225 void GetNameOfOwner(Owner owner, TileIndex tile)
    00226 {
    00227   SetDParam(2, owner);
    00228
    00229   if (owner != OWNER_TOWN) {
    00230     if (!Company::IsValidID(owner)) {
    00231       SetDParam(0, STR_COMPANY_SOMEONE);
    00232     } else {
    00233       SetDParam(0, STR_COMPANY_NAME);
    00234       SetDParam(1, owner);
    00235     }
    00236   } else {
    00237     assert(tile != 0);
    00238     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
    00239
    00240     SetDParam(0, STR_TOWN_NAME);
    00241     SetDParam(1, t->index);
    00242   }
    00243 }
    00244
    00245
    00254 bool CheckOwnership(Owner owner, TileIndex tile)
    00255 {
    00256   assert(owner < OWNER_END);
    00257   assert(owner != OWNER_TOWN || tile != 0);
    00258
    00259   if (owner == _current_company) return true;
    00260   _error_message = STR_ERROR_OWNED_BY;
    00261   GetNameOfOwner(owner, tile);
    00262   return false;
    00263 }
    00264
    00272 bool CheckTileOwnership(TileIndex tile)
    00273 {
    00274   Owner owner = GetTileOwner(tile);
    00275
    00276   assert(owner < OWNER_END);
    00277
    00278   if (owner == _current_company) return true;
    00279   _error_message = STR_ERROR_OWNED_BY;
    00280
    00281   /* no need to get the name of the owner unless we're the local company (saves some time) */
    00282   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
    00283   return false;
    00284 }
    00285
    00286 static void GenerateCompanyName(Company *c)
    00287 {
    00288   TileIndex tile;
    00289   Town *t;
    00290   StringID str;
    00291   Company *cc;
    00292   uint32 strp;
    00293   /* Reserve space for extra unicode character. We need to do this to be able
    00294    * to detect too long company name. */
    00295   char buffer[MAX_LENGTH_COMPANY_NAME_BYTES + MAX_CHAR_LENGTH];
    00296
    00297   if (c->name_1 != STR_SV_UNNAMED) return;
    00298
    00299   tile = c->last_build_coordinate;
    00300   if (tile == 0) return;
    00301
    00302   t = ClosestTownFromTile(tile, UINT_MAX);
    00303
    00304   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
    00305     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_PLAYERNAME_START;
    00306     strp = t->townnameparts;
    00307
    00308 verify_name:;
    00309     /* No companies must have this name already */
    00310     FOR_ALL_COMPANIES(cc) {
    00311       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
    00312     }
    00313
    00314     GetString(buffer, str, lastof(buffer));
    00315     if (strlen(buffer) >= MAX_LENGTH_COMPANY_NAME_BYTES) goto bad_town_name;
    00316
    00317 set_name:;
    00318     c->name_1 = str;
    00319     c->name_2 = strp;
    00320
    00321     MarkWholeScreenDirty();
    00322
    00323     if (c->is_ai) {
    00324       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00325       cni->FillData(c);
    00326       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
    00327       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
    00328       SetDParamStr(2, cni->company_name);
    00329       SetDParam(3, t->index);
    00330       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
    00331     }
    00332     AI::BroadcastNewEvent(new AIEventCompanyNew(c->index), c->index);
    00333     return;
    00334   }
    00335 bad_town_name:;
    00336
    00337   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
    00338     str = SPECSTR_ANDCO_NAME;
    00339     strp = c->president_name_2;
    00340     goto set_name;
    00341   } else {
    00342     str = SPECSTR_ANDCO_NAME;
    00343     strp = Random();
    00344     goto verify_name;
    00345   }
    00346 }
    00347
    00348 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
    00349 static const Colours _similar_colour[COLOUR_END][2] = {
    00350   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
    00351   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
    00352   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
    00353   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
    00354   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
    00355   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
    00356   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
    00357   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
    00358   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
    00359   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
    00360   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
    00361   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
    00362   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
    00363   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
    00364   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
    00365   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
    00366 };
    00367
    00368 static Colours GenerateCompanyColour()
    00369 {
    00370   Colours colours[COLOUR_END];
    00371
    00372   /* Initialize array */
    00373   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
    00374
    00375   /* And randomize it */
    00376   for (uint i = 0; i < 100; i++) {
    00377     uint r = Random();
    00378     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
    00379   }
    00380
    00381   /* Bubble sort it according to the values in table 1 */
    00382   for (uint i = 0; i < COLOUR_END; i++) {
    00383     for (uint j = 1; j < COLOUR_END; j++) {
    00384       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
    00385         Swap(colours[j - 1], colours[j]);
    00386       }
    00387     }
    00388   };
    00389
    00390   /* Move the colours that look similar to each company's colour to the side */
    00391   Company *c;
    00392   FOR_ALL_COMPANIES(c) {
    00393     Colours pcolour = (Colours)c->colour;
    00394
    00395     for (uint i = 0; i < COLOUR_END; i++) {
    00396       if (colours[i] == pcolour) {
    00397         colours[i] = INVALID_COLOUR;
    00398         break;
    00399       }
    00400     }
    00401
    00402     for (uint j = 0; j < 2; j++) {
    00403       Colours similar = _similar_colour[pcolour][j];
    00404       if (similar == INVALID_COLOUR) break;
    00405
    00406       for (uint i = 1; i < COLOUR_END; i++) {
    00407         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
    00408       }
    00409     }
    00410   }
    00411
    00412   /* Return the first available colour */
    00413   for (uint i = 0; i < COLOUR_END; i++) {
    00414     if (colours[i] != INVALID_COLOUR) return colours[i];
    00415   }
    00416
    00417   NOT_REACHED();
    00418 }
    00419
    00420 static void GeneratePresidentName(Company *c)
    00421 {
    00422   for (;;) {
    00423 restart:;
    00424     c->president_name_2 = Random();
    00425     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00426
    00427     /* Reserve space for extra unicode character. We need to do this to be able
    00428      * to detect too long president name. */
    00429     char buffer[MAX_LENGTH_PRESIDENT_NAME_BYTES + MAX_CHAR_LENGTH];
    00430     SetDParam(0, c->index);
    00431     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
    00432     if (strlen(buffer) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) continue;
    00433
    00434     Company *cc;
    00435     FOR_ALL_COMPANIES(cc) {
    00436       if (c != cc) {
    00437         /* Reserve extra space so even overlength president names can be compared. */
    00438         char buffer2[MAX_LENGTH_PRESIDENT_NAME_BYTES + MAX_CHAR_LENGTH];
    00439         SetDParam(0, cc->index);
    00440         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
    00441         if (strcmp(buffer2, buffer) == 0) goto restart;
    00442       }
    00443     }
    00444     return;
    00445   }
    00446 }
    00447
    00448 void ResetCompanyLivery(Company *c)
    00449 {
    00450   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
    00451     c->livery[scheme].in_use  = false;
    00452     c->livery[scheme].colour1 = c->colour;
    00453     c->livery[scheme].colour2 = c->colour;
    00454   }
    00455 }
    00456
    00464 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
    00465 {
    00466   if (!Company::CanAllocateItem()) return NULL;
    00467
    00468   /* we have to generate colour before this company is valid */
    00469   Colours colour = GenerateCompanyColour();
    00470
    00471   Company *c;
    00472   if (company == INVALID_COMPANY) {
    00473     c = new Company(STR_SV_UNNAMED, is_ai);
    00474   } else {
    00475     if (Company::IsValidID(company)) return NULL;
    00476     c = new (company) Company(STR_SV_UNNAMED, is_ai);
    00477   }
    00478
    00479   c->colour = colour;
    00480
    00481   ResetCompanyLivery(c);
    00482   _company_colours[c->index] = (Colours)c->colour;
    00483
    00484   c->money = c->current_loan = 100000;
    00485
    00486   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
    00487
    00488   c->avail_railtypes = GetCompanyRailtypes(c->index);
    00489   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    00490   c->inaugurated_year = _cur_year;
    00491   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
    00492
    00493   SetDefaultCompanySettings(c->index);
    00494
    00495   GeneratePresidentName(c);
    00496
    00497   SetWindowDirty(WC_GRAPH_LEGEND, 0);
    00498   SetWindowDirty(WC_TOOLBAR_MENU, 0);
    00499   SetWindowDirty(WC_CLIENT_LIST, 0);
    00500
    00501   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
    00502
    00503   c->num_engines = CallocT<uint16>(Engine::GetPoolSize());
    00504
    00505   return c;
    00506 }
    00507
    00508 void StartupCompanies()
    00509 {
    00510   _next_competitor_start = 0;
    00511 }
    00512
    00513 #ifdef ENABLE_AI
    00514 static void MaybeStartNewCompany()
    00515 {
    00516 #ifdef ENABLE_NETWORK
    00517   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
    00518 #endif /* ENABLE_NETWORK */
    00519
    00520   Company *c;
    00521
    00522   /* count number of competitors */
    00523   uint n = 0;
    00524   FOR_ALL_COMPANIES(c) {
    00525     if (c->is_ai) n++;
    00526   }
    00527
    00528   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
    00529     /* Send a command to all clients to start up a new AI.
    00530      * Works fine for Multiplayer and Singleplayer */
    00531     DoCommandP(0, 1, INVALID_COMPANY, CMD_COMPANY_CTRL);
    00532   }
    00533 }
    00534 #endif /* ENABLE_AI */
    00535
    00536 void InitializeCompanies()
    00537 {
    00538   _company_pool.CleanPool();
    00539   _cur_company_tick_index = 0;
    00540 }
    00541
    00551 static void HandleBankruptcyTakeover(Company *c)
    00552 {
    00553   /* Amount of time out for each company to take over a company;
    00554    * Timeout is a quarter (3 months of 30 days) divided over the
    00555    * number of companies. The minimum number of days in a quarter
    00556    * is 90: 31 in January, 28 in February and 31 in March.
    00557    * Note that the company going bankrupt can't buy itself. */
    00558   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
    00559
    00560   assert(c->bankrupt_asked != 0);
    00561
    00562   /* We're currently asking some company to buy 'us' */
    00563   if (c->bankrupt_timeout != 0) {
    00564     c->bankrupt_timeout -= MAX_COMPANIES;
    00565     if (c->bankrupt_timeout > 0) return;
    00566     c->bankrupt_timeout = 0;
    00567
    00568     return;
    00569   }
    00570
    00571   /* Did we ask everyone for bankruptcy? If so, bail out. */
    00572   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
    00573
    00574   Company *c2, *best = NULL;
    00575   int32 best_performance = -1;
    00576
    00577   /* Ask the company with the highest performance history first */
    00578   FOR_ALL_COMPANIES(c2) {
    00579     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
    00580         !HasBit(c->bankrupt_asked, c2->index) &&
    00581         best_performance < c2->old_economy[1].performance_history) {
    00582       best_performance = c2->old_economy[1].performance_history;
    00583       best = c2;
    00584     }
    00585   }
    00586
    00587   /* Asked all companies? */
    00588   if (best_performance == -1) {
    00589     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
    00590     return;
    00591   }
    00592
    00593   SetBit(c->bankrupt_asked, best->index);
    00594
    00595   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
    00596   if (best->is_ai) {
    00597     AI::NewEvent(best->index, new AIEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
    00598   } else if (IsInteractiveCompany(best->index)) {
    00599     ShowBuyCompanyDialog(c->index);
    00600   }
    00601 }
    00602
    00603 void OnTick_Companies()
    00604 {
    00605   if (_game_mode == GM_EDITOR) return;
    00606
    00607   Company *c = Company::GetIfValid(_cur_company_tick_index);
    00608   if (c != NULL) {
    00609     if (c->name_1 != 0) GenerateCompanyName(c);
    00610     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
    00611   }
    00612
    00613 #ifdef ENABLE_AI
    00614   if (_next_competitor_start == 0) {
    00615     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
    00616   }
    00617
    00618   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
    00619     MaybeStartNewCompany();
    00620   }
    00621 #endif /* ENABLE_AI */
    00622
    00623   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
    00624 }
    00625
    00626 void CompaniesYearlyLoop()
    00627 {
    00628   Company *c;
    00629
    00630   /* Copy statistics */
    00631   FOR_ALL_COMPANIES(c) {
    00632     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
    00633     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
    00634     SetWindowDirty(WC_FINANCES, c->index);
    00635   }
    00636
    00637   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
    00638     ShowCompanyFinances(_local_company);
    00639     c = Company::Get(_local_company);
    00640     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
    00641       SndPlayFx(SND_01_BAD_YEAR);
    00642     } else {
    00643       SndPlayFx(SND_00_GOOD_YEAR);
    00644     }
    00645   }
    00646 }
    00647
    00659 CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00660 {
    00661   Company *c = Company::GetIfValid(_current_company);
    00662   if (c == NULL) return CMD_ERROR;
    00663
    00664   EngineID old_engine_type = GB(p2, 0, 16);
    00665   EngineID new_engine_type = GB(p2, 16, 16);
    00666   GroupID id_g = GB(p1, 16, 16);
    00667   CommandCost cost;
    00668
    00669   if (!Group::IsValidID(id_g) && !IsAllGroupID(id_g) && !IsDefaultGroupID(id_g)) return CMD_ERROR;
    00670   if (!Engine::IsValidID(old_engine_type)) return CMD_ERROR;
    00671
    00672   if (new_engine_type != INVALID_ENGINE) {
    00673     if (!Engine::IsValidID(new_engine_type)) return CMD_ERROR;
    00674     if (!CheckAutoreplaceValidity(old_engine_type, new_engine_type, _current_company)) return CMD_ERROR;
    00675
    00676     cost = AddEngineReplacementForCompany(c, old_engine_type, new_engine_type, id_g, flags);
    00677   } else {
    00678     cost = RemoveEngineReplacementForCompany(c, old_engine_type, id_g, flags);
    00679   }
    00680
    00681   if ((flags & DC_EXEC) && IsLocalCompany()) InvalidateAutoreplaceWindow(old_engine_type, id_g);
    00682
    00683   return cost;
    00684 }
    00685
    00691 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
    00692 {
    00693   SetDParam(0, c->index);
    00694   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
    00695
    00696   if (other == NULL) {
    00697     *this->other_company_name = '\0';
    00698   } else {
    00699     SetDParam(0, other->index);
    00700     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
    00701     c = other;
    00702   }
    00703
    00704   SetDParam(0, c->index);
    00705   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
    00706
    00707   this->colour = c->colour;
    00708   this->face = c->face;
    00709
    00710 }
    00711
    00733 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00734 {
    00735   if (flags & DC_EXEC) _current_company = OWNER_NONE;
    00736
    00737   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
    00738
    00739   switch (p1) {
    00740     case 0: { // Create a new company
    00741       /* This command is only executed in a multiplayer game */
    00742       if (!_networking) return CMD_ERROR;
    00743
    00744 #ifdef ENABLE_NETWORK
    00745
    00746       /* Joining Client:
    00747        * _local_company: COMPANY_SPECTATOR
    00748        * cid = clientid
    00749        *
    00750        * Other client(s)/server:
    00751        * _local_company: what they play as
    00752        * cid = requested company/company of joining client */
    00753       ClientID cid = (ClientID)p2;
    00754
    00755       /* Has the network client a correct ClientIndex? */
    00756       if (!(flags & DC_EXEC)) return CommandCost();
    00757       NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(cid);
    00758       if (ci == NULL) return CommandCost();
    00759
    00760       /* Delete multiplayer progress bar */
    00761       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
    00762
    00763       Company *c = DoStartupNewCompany(false);
    00764
    00765       /* A new company could not be created, revert to being a spectator */
    00766       if (c == NULL) {
    00767         if (_network_server) {
    00768           ci->client_playas = COMPANY_SPECTATOR;
    00769           NetworkUpdateClientInfo(ci->client_id);
    00770         }
    00771         break;
    00772       }
    00773
    00774       /* This is the client (or non-dedicated server) who wants a new company */
    00775       if (cid == _network_own_client_id) {
    00776         assert(_local_company == COMPANY_SPECTATOR);
    00777         SetLocalCompany(c->index);
    00778         if (!StrEmpty(_settings_client.network.default_company_pass)) {
    00779           NetworkChangeCompanyPassword(_settings_client.network.default_company_pass);
    00780         }
    00781
    00782         _current_company = _local_company;
    00783
    00784         /* Now that we have a new company, broadcast our company settings to
    00785          * all clients so everything is in sync */
    00786         SyncCompanySettings();
    00787
    00788         MarkWholeScreenDirty();
    00789       }
    00790
    00791       if (_network_server) {
    00792         /* XXX - UGLY! p2 (pid) is mis-used to fetch the client-id, done at
    00793          * server side in network_server.c:838, function
    00794          * DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND) */
    00795         CompanyID old_playas = ci->client_playas;
    00796         ci->client_playas = c->index;
    00797         NetworkUpdateClientInfo(ci->client_id);
    00798
    00799         if (Company::IsValidID(ci->client_playas)) {
    00800           _network_company_states[c->index].months_empty = 0;
    00801           _network_company_states[c->index].password[0] = '\0';
    00802           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
    00803
    00804           /* XXX - When a client joins, we automatically set its name to the
    00805            * client's name (for some reason). As it stands now only the server
    00806            * knows the client's name, so it needs to send out a "broadcast" to
    00807            * do this. To achieve this we send a network command. However, it
    00808            * uses _local_company to execute the command as.  To prevent abuse
    00809            * (eg. only yourself can change your name/company), we 'cheat' by
    00810            * impersonation _local_company as the server. Not the best solution;
    00811            * but it works.
    00812            * TODO: Perhaps this could be improved by when the client is ready
    00813            * with joining to let it send itself the command, and not the server?
    00814            * For example in network_client.c:534? */
    00815           NetworkSend_Command(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
    00816         }
    00817
    00818         /* Announce new company on network, if the client was a SPECTATOR before */
    00819         if (old_playas == COMPANY_SPECTATOR) {
    00820           NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
    00821         }
    00822       }
    00823 #endif /* ENABLE_NETWORK */
    00824     } break;
    00825
    00826     case 1: // Make a new AI company
    00827       if (!(flags & DC_EXEC)) return CommandCost();
    00828
    00829       if (p2 != INVALID_COMPANY && (p2 >= MAX_COMPANIES || Company::IsValidID(p2))) return CMD_ERROR;
    00830       DoStartupNewCompany(true, (CompanyID)p2);
    00831       break;
    00832
    00833     case 2: { // Delete a company
    00834       Company *c = Company::GetIfValid(p2);
    00835       if (c == NULL) return CMD_ERROR;
    00836
    00837       if (!(flags & DC_EXEC)) return CommandCost();
    00838
    00839       /* Delete any open window of the company */
    00840       DeleteCompanyWindows(c->index);
    00841       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
    00842       cni->FillData(c);
    00843
    00844       /* Show the bankrupt news */
    00845       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
    00846       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
    00847       SetDParamStr(2, cni->company_name);
    00848       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
    00849
    00850       /* Remove the company */
    00851       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
    00852       if (c->is_ai) AI::Stop(c->index);
    00853
    00854       CompanyID c_index = c->index;
    00855       delete c;
    00856       AI::BroadcastNewEvent(new AIEventCompanyBankrupt(c_index));
    00857     } break;
    00858
    00859     default: return CMD_ERROR;
    00860   }
    00861
    00862   return CommandCost();
    00863 }
    00864
    00873 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00874 {
    00875   CompanyManagerFace cmf = (CompanyManagerFace)p2;
    00876
    00877   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
    00878
    00879   if (flags & DC_EXEC) {
    00880     Company::Get(_current_company)->face = cmf;
    00881     MarkWholeScreenDirty();
    00882   }
    00883   return CommandCost();
    00884 }
    00885
    00896 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00897 {
    00898   Colours colour = Extract<Colours, 0, 4>(p2);
    00899   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
    00900   byte state = GB(p1, 8, 2);
    00901
    00902   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
    00903
    00904   Company *c = Company::Get(_current_company);
    00905
    00906   /* Ensure no two companies have the same primary colour */
    00907   if (scheme == LS_DEFAULT && state == 0) {
    00908     const Company *cc;
    00909     FOR_ALL_COMPANIES(cc) {
    00910       if (cc != c && cc->colour == colour) return CMD_ERROR;
    00911     }
    00912   }
    00913
    00914   if (flags & DC_EXEC) {
    00915     switch (state) {
    00916       case 0:
    00917         c->livery[scheme].colour1 = colour;
    00918
    00919         /* If setting the first colour of the default scheme, adjust the
    00920          * original and cached company colours too. */
    00921         if (scheme == LS_DEFAULT) {
    00922           _company_colours[_current_company] = colour;
    00923           c->colour = colour;
    00924         }
    00925         break;
    00926
    00927       case 1:
    00928         c->livery[scheme].colour2 = colour;
    00929         break;
    00930
    00931       case 2:
    00932         c->livery[scheme].in_use = colour != 0;
    00933
    00934         /* Now handle setting the default scheme's in_use flag.
    00935          * This is different to the other schemes, as it signifies if any
    00936          * scheme is active at all. If this flag is not set, then no
    00937          * processing of vehicle types occurs at all, and only the default
    00938          * colours will be used. */
    00939
    00940         /* If enabling a scheme, set the default scheme to be in use too */
    00941         if (colour != 0) {
    00942           c->livery[LS_DEFAULT].in_use = true;
    00943           break;
    00944         }
    00945
    00946         /* Else loop through all schemes to see if any are left enabled.
    00947          * If not, disable the default scheme too. */
    00948         c->livery[LS_DEFAULT].in_use = false;
    00949         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
    00950           if (c->livery[scheme].in_use) {
    00951             c->livery[LS_DEFAULT].in_use = true;
    00952             break;
    00953           }
    00954         }
    00955         break;
    00956
    00957       default:
    00958         break;
    00959     }
    00960     ResetVehicleColourMap();
    00961     MarkWholeScreenDirty();
    00962
    00963     /* All graph related to companies use the company colour. */
    00964     InvalidateWindowData(WC_INCOME_GRAPH, 0);
    00965     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
    00966     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
    00967     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
    00968     InvalidateWindowData(WC_COMPANY_VALUE, 0);
    00969
    00970     /* Company colour data is indirectly cached. */
    00971     Vehicle *v;
    00972     FOR_ALL_VEHICLES(v) {
    00973       if (v->owner == _current_company) v->InvalidateNewGRFCache();
    00974     }
    00975   }
    00976   return CommandCost();
    00977 }
    00978
    00979 static bool IsUniqueCompanyName(const char *name)
    00980 {
    00981   const Company *c;
    00982
    00983   FOR_ALL_COMPANIES(c) {
    00984     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
    00985   }
    00986
    00987   return true;
    00988 }
    00989
    00998 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    00999 {
    01000   bool reset = StrEmpty(text);
    01001
    01002   if (!reset) {
    01003     if (strlen(text) >= MAX_LENGTH_COMPANY_NAME_BYTES) return CMD_ERROR;
    01004     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01005   }
    01006
    01007   if (flags & DC_EXEC) {
    01008     Company *c = Company::Get(_current_company);
    01009     free(c->name);
    01010     c->name = reset ? NULL : strdup(text);
    01011     MarkWholeScreenDirty();
    01012   }
    01013
    01014   return CommandCost();
    01015 }
    01016
    01017 static bool IsUniquePresidentName(const char *name)
    01018 {
    01019   const Company *c;
    01020
    01021   FOR_ALL_COMPANIES(c) {
    01022     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
    01023   }
    01024
    01025   return true;
    01026 }
    01027
    01036 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01037 {
    01038   bool reset = StrEmpty(text);
    01039
    01040   if (!reset) {
    01041     if (strlen(text) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) return CMD_ERROR;
    01042     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
    01043   }
    01044
    01045   if (flags & DC_EXEC) {
    01046     Company *c = Company::Get(_current_company);
    01047     free(c->president_name);
    01048
    01049     if (reset) {
    01050       c->president_name = NULL;
    01051     } else {
    01052       c->president_name = strdup(text);
    01053
    01054       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
    01055         char buf[80];
    01056
    01057         snprintf(buf, lengthof(buf), "%s Transport", text);
    01058         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
    01059       }
    01060     }
    01061
    01062     MarkWholeScreenDirty();
    01063   }
    01064
    01065   return CommandCost();
    01066 }