# company_cmd.cpp

Go to the documentation of this file.

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