company_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: company_cmd.cpp 23741 2012-01-03 21:47:01Z 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 "company_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 "network/network_admin.h"
00024 #include "ai/ai.hpp"
00025 #include "company_manager_face.h"
00026 #include "window_func.h"
00027 #include "strings_func.h"
00028 #include "date_func.h"
00029 #include "sound_func.h"
00030 #include "rail.h"
00031 #include "core/pool_func.hpp"
00032 #include "settings_func.h"
00033 #include "vehicle_base.h"
00034 #include "vehicle_func.h"
00035 #include "smallmap_gui.h"
00036 #include "game/game.hpp"
00037 
00038 #include "table/strings.h"
00039 
00040 CompanyByte _local_company;   
00041 CompanyByte _current_company; 
00042 Colours _company_colours[MAX_COMPANIES];  
00043 CompanyManagerFace _company_manager_face; 
00044 uint _next_competitor_start;              
00045 uint _cur_company_tick_index;             
00046 
00047 CompanyPool _company_pool("Company"); 
00048 INSTANTIATE_POOL_METHODS(Company)
00049 
00050 
00055 Company::Company(uint16 name_1, bool is_ai)
00056 {
00057   this->name_1 = name_1;
00058   this->location_of_HQ = INVALID_TILE;
00059   this->is_ai = is_ai;
00060   this->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
00061   this->clear_limit     = _settings_game.construction.clear_frame_burst << 16;
00062 
00063   for (uint j = 0; j < 4; j++) this->share_owners[j] = COMPANY_SPECTATOR;
00064   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, INVALID_COMPANY);
00065 }
00066 
00068 Company::~Company()
00069 {
00070   if (CleaningPool()) return;
00071 
00072   DeleteCompanyWindows(this->index);
00073 }
00074 
00079 void Company::PostDestructor(size_t index)
00080 {
00081   InvalidateWindowData(WC_GRAPH_LEGEND, 0, (int)index);
00082   InvalidateWindowData(WC_PERFORMANCE_DETAIL, 0, (int)index);
00083   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00084   /* If the currently shown error message has this company in it, then close it. */
00085   InvalidateWindowData(WC_ERRMSG, 0);
00086 }
00087 
00094 void SetLocalCompany(CompanyID new_company)
00095 {
00096   /* company could also be COMPANY_SPECTATOR or OWNER_NONE */
00097   assert(Company::IsValidID(new_company) || new_company == COMPANY_SPECTATOR || new_company == OWNER_NONE);
00098 
00099 #ifdef ENABLE_NETWORK
00100   /* Delete the chat window, if you were team chatting. */
00101   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_TEAM, _local_company);
00102 #endif
00103 
00104   assert(IsLocalCompany());
00105 
00106   _current_company = _local_company = new_company;
00107 
00108   /* Delete any construction windows... */
00109   DeleteConstructionWindows();
00110 
00111   /* ... and redraw the whole screen. */
00112   MarkWholeScreenDirty();
00113   InvalidateWindowClassesData(WC_SIGN_LIST, -1);
00114 }
00115 
00121 TextColour GetDrawStringCompanyColour(CompanyID company)
00122 {
00123   if (!Company::IsValidID(company)) return (TextColour)_colour_gradient[COLOUR_WHITE][4] | TC_IS_PALETTE_COLOUR;
00124   return (TextColour)_colour_gradient[_company_colours[company]][4] | TC_IS_PALETTE_COLOUR;
00125 }
00126 
00133 void DrawCompanyIcon(CompanyID c, int x, int y)
00134 {
00135   DrawSprite(SPR_COMPANY_ICON, COMPANY_SPRITE_COLOUR(c), x, y);
00136 }
00137 
00144 static bool IsValidCompanyManagerFace(CompanyManagerFace cmf)
00145 {
00146   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_GEN_ETHN, GE_WM)) return false;
00147 
00148   GenderEthnicity ge   = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
00149   bool has_moustache   = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE,   ge) != 0;
00150   bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
00151   bool has_glasses     = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
00152 
00153   if (!AreCompanyManagerFaceBitsValid(cmf, CMFV_EYE_COLOUR, ge)) return false;
00154   for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
00155     switch (cmfv) {
00156       case CMFV_MOUSTACHE:   if (!has_moustache)   continue; break;
00157       case CMFV_LIPS:        // FALL THROUGH
00158       case CMFV_NOSE:        if (has_moustache)    continue; break;
00159       case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
00160       case CMFV_GLASSES:     if (!has_glasses)     continue; break;
00161       default: break;
00162     }
00163     if (!AreCompanyManagerFaceBitsValid(cmf, cmfv, ge)) return false;
00164   }
00165 
00166   return true;
00167 }
00168 
00173 void InvalidateCompanyWindows(const Company *company)
00174 {
00175   CompanyID cid = company->index;
00176 
00177   if (cid == _local_company) SetWindowDirty(WC_STATUS_BAR, 0);
00178   SetWindowDirty(WC_FINANCES, cid);
00179 }
00180 
00186 bool CheckCompanyHasMoney(CommandCost &cost)
00187 {
00188   if (cost.GetCost() > 0) {
00189     const Company *c = Company::GetIfValid(_current_company);
00190     if (c != NULL && cost.GetCost() > c->money) {
00191       SetDParam(0, cost.GetCost());
00192       cost.MakeError(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY);
00193       return false;
00194     }
00195   }
00196   return true;
00197 }
00198 
00204 static void SubtractMoneyFromAnyCompany(Company *c, CommandCost cost)
00205 {
00206   if (cost.GetCost() == 0) return;
00207   assert(cost.GetExpensesType() != INVALID_EXPENSES);
00208 
00209   c->money -= cost.GetCost();
00210   c->yearly_expenses[0][cost.GetExpensesType()] += cost.GetCost();
00211 
00212   if (HasBit(1 << EXPENSES_TRAIN_INC    |
00213              1 << EXPENSES_ROADVEH_INC  |
00214              1 << EXPENSES_AIRCRAFT_INC |
00215              1 << EXPENSES_SHIP_INC, cost.GetExpensesType())) {
00216     c->cur_economy.income -= cost.GetCost();
00217   } else if (HasBit(1 << EXPENSES_TRAIN_RUN    |
00218                     1 << EXPENSES_ROADVEH_RUN  |
00219                     1 << EXPENSES_AIRCRAFT_RUN |
00220                     1 << EXPENSES_SHIP_RUN     |
00221                     1 << EXPENSES_PROPERTY     |
00222                     1 << EXPENSES_LOAN_INT, cost.GetExpensesType())) {
00223     c->cur_economy.expenses -= cost.GetCost();
00224   }
00225 
00226   InvalidateCompanyWindows(c);
00227 }
00228 
00233 void SubtractMoneyFromCompany(CommandCost cost)
00234 {
00235   Company *c = Company::GetIfValid(_current_company);
00236   if (c != NULL) SubtractMoneyFromAnyCompany(c, cost);
00237 }
00238 
00244 void SubtractMoneyFromCompanyFract(CompanyID company, CommandCost cst)
00245 {
00246   Company *c = Company::Get(company);
00247   byte m = c->money_fraction;
00248   Money cost = cst.GetCost();
00249 
00250   c->money_fraction = m - (byte)cost;
00251   cost >>= 8;
00252   if (c->money_fraction > m) cost++;
00253   if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
00254 }
00255 
00257 void UpdateLandscapingLimits()
00258 {
00259   Company *c;
00260   FOR_ALL_COMPANIES(c) {
00261     c->terraform_limit = min(c->terraform_limit + _settings_game.construction.terraform_per_64k_frames, (uint32)_settings_game.construction.terraform_frame_burst << 16);
00262     c->clear_limit     = min(c->clear_limit     + _settings_game.construction.clear_per_64k_frames,     (uint32)_settings_game.construction.clear_frame_burst << 16);
00263   }
00264 }
00265 
00272 void GetNameOfOwner(Owner owner, TileIndex tile)
00273 {
00274   SetDParam(2, owner);
00275 
00276   if (owner != OWNER_TOWN) {
00277     if (!Company::IsValidID(owner)) {
00278       SetDParam(0, STR_COMPANY_SOMEONE);
00279     } else {
00280       SetDParam(0, STR_COMPANY_NAME);
00281       SetDParam(1, owner);
00282     }
00283   } else {
00284     assert(tile != 0);
00285     const Town *t = ClosestTownFromTile(tile, UINT_MAX);
00286 
00287     SetDParam(0, STR_TOWN_NAME);
00288     SetDParam(1, t->index);
00289   }
00290 }
00291 
00292 
00301 CommandCost CheckOwnership(Owner owner, TileIndex tile)
00302 {
00303   assert(owner < OWNER_END);
00304   assert(owner != OWNER_TOWN || tile != 0);
00305 
00306   if (owner == _current_company) return CommandCost();
00307 
00308   GetNameOfOwner(owner, tile);
00309   return_cmd_error(STR_ERROR_OWNED_BY);
00310 }
00311 
00319 CommandCost CheckTileOwnership(TileIndex tile)
00320 {
00321   Owner owner = GetTileOwner(tile);
00322 
00323   assert(owner < OWNER_END);
00324 
00325   if (owner == _current_company) return CommandCost();
00326 
00327   /* no need to get the name of the owner unless we're the local company (saves some time) */
00328   if (IsLocalCompany()) GetNameOfOwner(owner, tile);
00329   return_cmd_error(STR_ERROR_OWNED_BY);
00330 }
00331 
00336 static void GenerateCompanyName(Company *c)
00337 {
00338   /* Reserve space for extra unicode character. We need to do this to be able
00339    * to detect too long company name. */
00340   char buffer[(MAX_LENGTH_COMPANY_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00341 
00342   if (c->name_1 != STR_SV_UNNAMED) return;
00343   if (c->last_build_coordinate == 0) return;
00344 
00345   Town *t = ClosestTownFromTile(c->last_build_coordinate, UINT_MAX);
00346 
00347   StringID str;
00348   uint32 strp;
00349   if (t->name == NULL && IsInsideMM(t->townnametype, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_LAST + 1)) {
00350     str = t->townnametype - SPECSTR_TOWNNAME_START + SPECSTR_COMPANY_NAME_START;
00351     strp = t->townnameparts;
00352 
00353 verify_name:;
00354     /* No companies must have this name already */
00355     Company *cc;
00356     FOR_ALL_COMPANIES(cc) {
00357       if (cc->name_1 == str && cc->name_2 == strp) goto bad_town_name;
00358     }
00359 
00360     GetString(buffer, str, lastof(buffer));
00361     if (Utf8StringLength(buffer) >= MAX_LENGTH_COMPANY_NAME_CHARS) goto bad_town_name;
00362 
00363 set_name:;
00364     c->name_1 = str;
00365     c->name_2 = strp;
00366 
00367     MarkWholeScreenDirty();
00368 
00369     if (c->is_ai) {
00370       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00371       cni->FillData(c);
00372       SetDParam(0, STR_NEWS_COMPANY_LAUNCH_TITLE);
00373       SetDParam(1, STR_NEWS_COMPANY_LAUNCH_DESCRIPTION);
00374       SetDParamStr(2, cni->company_name);
00375       SetDParam(3, t->index);
00376       AddNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_NEW, NR_TILE, c->last_build_coordinate, NR_NONE, UINT32_MAX, cni);
00377     }
00378     return;
00379   }
00380 bad_town_name:;
00381 
00382   if (c->president_name_1 == SPECSTR_PRESIDENT_NAME) {
00383     str = SPECSTR_ANDCO_NAME;
00384     strp = c->president_name_2;
00385     goto set_name;
00386   } else {
00387     str = SPECSTR_ANDCO_NAME;
00388     strp = Random();
00389     goto verify_name;
00390   }
00391 }
00392 
00394 static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
00396 static const Colours _similar_colour[COLOUR_END][2] = {
00397   { COLOUR_BLUE,       COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
00398   { COLOUR_GREEN,      COLOUR_DARK_GREEN }, // COLOUR_PALE_GREEN
00399   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_PINK
00400   { COLOUR_ORANGE,     INVALID_COLOUR    }, // COLOUR_YELLOW
00401   { INVALID_COLOUR,    INVALID_COLOUR    }, // COLOUR_RED
00402   { COLOUR_DARK_BLUE,  COLOUR_BLUE       }, // COLOUR_LIGHT_BLUE
00403   { COLOUR_PALE_GREEN, COLOUR_DARK_GREEN }, // COLOUR_GREEN
00404   { COLOUR_PALE_GREEN, COLOUR_GREEN      }, // COLOUR_DARK_GREEN
00405   { COLOUR_DARK_BLUE,  COLOUR_LIGHT_BLUE }, // COLOUR_BLUE
00406   { COLOUR_BROWN,      COLOUR_ORANGE     }, // COLOUR_CREAM
00407   { COLOUR_PURPLE,     INVALID_COLOUR    }, // COLOUR_MAUVE
00408   { COLOUR_MAUVE,      INVALID_COLOUR    }, // COLOUR_PURPLE
00409   { COLOUR_YELLOW,     COLOUR_CREAM      }, // COLOUR_ORANGE
00410   { COLOUR_CREAM,      INVALID_COLOUR    }, // COLOUR_BROWN
00411   { COLOUR_WHITE,      INVALID_COLOUR    }, // COLOUR_GREY
00412   { COLOUR_GREY,       INVALID_COLOUR    }, // COLOUR_WHITE
00413 };
00414 
00419 static Colours GenerateCompanyColour()
00420 {
00421   Colours colours[COLOUR_END];
00422 
00423   /* Initialize array */
00424   for (uint i = 0; i < COLOUR_END; i++) colours[i] = (Colours)i;
00425 
00426   /* And randomize it */
00427   for (uint i = 0; i < 100; i++) {
00428     uint r = Random();
00429     Swap(colours[GB(r, 0, 4)], colours[GB(r, 4, 4)]);
00430   }
00431 
00432   /* Bubble sort it according to the values in table 1 */
00433   for (uint i = 0; i < COLOUR_END; i++) {
00434     for (uint j = 1; j < COLOUR_END; j++) {
00435       if (_colour_sort[colours[j - 1]] < _colour_sort[colours[j]]) {
00436         Swap(colours[j - 1], colours[j]);
00437       }
00438     }
00439   }
00440 
00441   /* Move the colours that look similar to each company's colour to the side */
00442   Company *c;
00443   FOR_ALL_COMPANIES(c) {
00444     Colours pcolour = (Colours)c->colour;
00445 
00446     for (uint i = 0; i < COLOUR_END; i++) {
00447       if (colours[i] == pcolour) {
00448         colours[i] = INVALID_COLOUR;
00449         break;
00450       }
00451     }
00452 
00453     for (uint j = 0; j < 2; j++) {
00454       Colours similar = _similar_colour[pcolour][j];
00455       if (similar == INVALID_COLOUR) break;
00456 
00457       for (uint i = 1; i < COLOUR_END; i++) {
00458         if (colours[i - 1] == similar) Swap(colours[i - 1], colours[i]);
00459       }
00460     }
00461   }
00462 
00463   /* Return the first available colour */
00464   for (uint i = 0; i < COLOUR_END; i++) {
00465     if (colours[i] != INVALID_COLOUR) return colours[i];
00466   }
00467 
00468   NOT_REACHED();
00469 }
00470 
00475 static void GeneratePresidentName(Company *c)
00476 {
00477   for (;;) {
00478 restart:;
00479     c->president_name_2 = Random();
00480     c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00481 
00482     /* Reserve space for extra unicode character. We need to do this to be able
00483      * to detect too long president name. */
00484     char buffer[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00485     SetDParam(0, c->index);
00486     GetString(buffer, STR_PRESIDENT_NAME, lastof(buffer));
00487     if (Utf8StringLength(buffer) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) continue;
00488 
00489     Company *cc;
00490     FOR_ALL_COMPANIES(cc) {
00491       if (c != cc) {
00492         /* Reserve extra space so even overlength president names can be compared. */
00493         char buffer2[(MAX_LENGTH_PRESIDENT_NAME_CHARS + 1) * MAX_CHAR_LENGTH];
00494         SetDParam(0, cc->index);
00495         GetString(buffer2, STR_PRESIDENT_NAME, lastof(buffer2));
00496         if (strcmp(buffer2, buffer) == 0) goto restart;
00497       }
00498     }
00499     return;
00500   }
00501 }
00502 
00508 void ResetCompanyLivery(Company *c)
00509 {
00510   for (LiveryScheme scheme = LS_BEGIN; scheme < LS_END; scheme++) {
00511     c->livery[scheme].in_use  = false;
00512     c->livery[scheme].colour1 = c->colour;
00513     c->livery[scheme].colour2 = c->colour;
00514   }
00515 }
00516 
00524 Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY)
00525 {
00526   if (!Company::CanAllocateItem()) return NULL;
00527 
00528   /* we have to generate colour before this company is valid */
00529   Colours colour = GenerateCompanyColour();
00530 
00531   Company *c;
00532   if (company == INVALID_COMPANY) {
00533     c = new Company(STR_SV_UNNAMED, is_ai);
00534   } else {
00535     if (Company::IsValidID(company)) return NULL;
00536     c = new (company) Company(STR_SV_UNNAMED, is_ai);
00537   }
00538 
00539   c->colour = colour;
00540 
00541   ResetCompanyLivery(c);
00542   _company_colours[c->index] = (Colours)c->colour;
00543 
00544   c->money = c->current_loan = (100000ll * _economy.inflation_prices >> 16) / 50000 * 50000;
00545 
00546   c->share_owners[0] = c->share_owners[1] = c->share_owners[2] = c->share_owners[3] = INVALID_OWNER;
00547 
00548   c->avail_railtypes = GetCompanyRailtypes(c->index);
00549   c->avail_roadtypes = GetCompanyRoadtypes(c->index);
00550   c->inaugurated_year = _cur_year;
00551   RandomCompanyManagerFaceBits(c->face, (GenderEthnicity)Random(), false); // create a random company manager face
00552 
00553   SetDefaultCompanySettings(c->index);
00554 
00555   GeneratePresidentName(c);
00556 
00557   SetWindowDirty(WC_GRAPH_LEGEND, 0);
00558   SetWindowClassesDirty(WC_CLIENT_LIST_POPUP);
00559   SetWindowDirty(WC_CLIENT_LIST, 0);
00560   BuildOwnerLegend();
00561   InvalidateWindowData(WC_SMALLMAP, 0, 1);
00562 
00563   if (is_ai && (!_networking || _network_server)) AI::StartNew(c->index);
00564 
00565   AI::BroadcastNewEvent(new ScriptEventCompanyNew(c->index), c->index);
00566   Game::NewEvent(new ScriptEventCompanyNew(c->index));
00567 
00568   return c;
00569 }
00570 
00572 void StartupCompanies()
00573 {
00574   _next_competitor_start = 0;
00575 }
00576 
00578 static void MaybeStartNewCompany()
00579 {
00580 #ifdef ENABLE_NETWORK
00581   if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
00582 #endif /* ENABLE_NETWORK */
00583 
00584   Company *c;
00585 
00586   /* count number of competitors */
00587   uint n = 0;
00588   FOR_ALL_COMPANIES(c) {
00589     if (c->is_ai) n++;
00590   }
00591 
00592   if (n < (uint)_settings_game.difficulty.max_no_competitors) {
00593     /* Send a command to all clients to start up a new AI.
00594      * Works fine for Multiplayer and Singleplayer */
00595     DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
00596   }
00597 }
00598 
00600 void InitializeCompanies()
00601 {
00602   _cur_company_tick_index = 0;
00603 }
00604 
00611 bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
00612 {
00613   const Company *c1 = Company::Get(cbig);
00614   const Company *c2 = Company::Get(csmall);
00615 
00616   /* Do the combined vehicle counts stay within the limits? */
00617   return c1->group_all[VEH_TRAIN].num_vehicle + c2->group_all[VEH_TRAIN].num_vehicle <= _settings_game.vehicle.max_trains &&
00618     c1->group_all[VEH_ROAD].num_vehicle     + c2->group_all[VEH_ROAD].num_vehicle     <= _settings_game.vehicle.max_roadveh &&
00619     c1->group_all[VEH_SHIP].num_vehicle     + c2->group_all[VEH_SHIP].num_vehicle     <= _settings_game.vehicle.max_ships &&
00620     c1->group_all[VEH_AIRCRAFT].num_vehicle + c2->group_all[VEH_AIRCRAFT].num_vehicle <= _settings_game.vehicle.max_aircraft;
00621 }
00622 
00632 static void HandleBankruptcyTakeover(Company *c)
00633 {
00634   /* Amount of time out for each company to take over a company;
00635    * Timeout is a quarter (3 months of 30 days) divided over the
00636    * number of companies. The minimum number of days in a quarter
00637    * is 90: 31 in January, 28 in February and 31 in March.
00638    * Note that the company going bankrupt can't buy itself. */
00639   static const int TAKE_OVER_TIMEOUT = 3 * 30 * DAY_TICKS / (MAX_COMPANIES - 1);
00640 
00641   assert(c->bankrupt_asked != 0);
00642 
00643   /* We're currently asking some company to buy 'us' */
00644   if (c->bankrupt_timeout != 0) {
00645     c->bankrupt_timeout -= MAX_COMPANIES;
00646     if (c->bankrupt_timeout > 0) return;
00647     c->bankrupt_timeout = 0;
00648 
00649     return;
00650   }
00651 
00652   /* Did we ask everyone for bankruptcy? If so, bail out. */
00653   if (c->bankrupt_asked == MAX_UVALUE(CompanyMask)) return;
00654 
00655   Company *c2, *best = NULL;
00656   int32 best_performance = -1;
00657 
00658   /* Ask the company with the highest performance history first */
00659   FOR_ALL_COMPANIES(c2) {
00660     if (c2->bankrupt_asked == 0 && // Don't ask companies going bankrupt themselves
00661         !HasBit(c->bankrupt_asked, c2->index) &&
00662         best_performance < c2->old_economy[1].performance_history &&
00663         MayCompanyTakeOver(c2->index, c->index)) {
00664       best_performance = c2->old_economy[1].performance_history;
00665       best = c2;
00666     }
00667   }
00668 
00669   /* Asked all companies? */
00670   if (best_performance == -1) {
00671     c->bankrupt_asked = MAX_UVALUE(CompanyMask);
00672     return;
00673   }
00674 
00675   SetBit(c->bankrupt_asked, best->index);
00676 
00677   c->bankrupt_timeout = TAKE_OVER_TIMEOUT;
00678   if (best->is_ai) {
00679     AI::NewEvent(best->index, new ScriptEventCompanyAskMerger(c->index, ClampToI32(c->bankrupt_value)));
00680   } else if (IsInteractiveCompany(best->index)) {
00681     ShowBuyCompanyDialog(c->index);
00682   }
00683 }
00684 
00686 void OnTick_Companies()
00687 {
00688   if (_game_mode == GM_EDITOR) return;
00689 
00690   Company *c = Company::GetIfValid(_cur_company_tick_index);
00691   if (c != NULL) {
00692     if (c->name_1 != 0) GenerateCompanyName(c);
00693     if (c->bankrupt_asked != 0) HandleBankruptcyTakeover(c);
00694   }
00695 
00696   if (_next_competitor_start == 0) {
00697     _next_competitor_start = AI::GetStartNextTime() * DAY_TICKS;
00698   }
00699 
00700   if (AI::CanStartNew() && _game_mode != GM_MENU && --_next_competitor_start == 0) {
00701     MaybeStartNewCompany();
00702   }
00703 
00704   _cur_company_tick_index = (_cur_company_tick_index + 1) % MAX_COMPANIES;
00705 }
00706 
00711 void CompaniesYearlyLoop()
00712 {
00713   Company *c;
00714 
00715   /* Copy statistics */
00716   FOR_ALL_COMPANIES(c) {
00717     memmove(&c->yearly_expenses[1], &c->yearly_expenses[0], sizeof(c->yearly_expenses) - sizeof(c->yearly_expenses[0]));
00718     memset(&c->yearly_expenses[0], 0, sizeof(c->yearly_expenses[0]));
00719     SetWindowDirty(WC_FINANCES, c->index);
00720   }
00721 
00722   if (_settings_client.gui.show_finances && _local_company != COMPANY_SPECTATOR) {
00723     ShowCompanyFinances(_local_company);
00724     c = Company::Get(_local_company);
00725     if (c->num_valid_stat_ent > 5 && c->old_economy[0].performance_history < c->old_economy[4].performance_history) {
00726       SndPlayFx(SND_01_BAD_YEAR);
00727     } else {
00728       SndPlayFx(SND_00_GOOD_YEAR);
00729     }
00730   }
00731 }
00732 
00738 void CompanyNewsInformation::FillData(const Company *c, const Company *other)
00739 {
00740   SetDParam(0, c->index);
00741   GetString(this->company_name, STR_COMPANY_NAME, lastof(this->company_name));
00742 
00743   if (other == NULL) {
00744     *this->other_company_name = '\0';
00745   } else {
00746     SetDParam(0, other->index);
00747     GetString(this->other_company_name, STR_COMPANY_NAME, lastof(this->other_company_name));
00748     c = other;
00749   }
00750 
00751   SetDParam(0, c->index);
00752   GetString(this->president_name, STR_PRESIDENT_NAME_MANAGER, lastof(this->president_name));
00753 
00754   this->colour = c->colour;
00755   this->face = c->face;
00756 
00757 }
00758 
00763 void CompanyAdminUpdate(const Company *company)
00764 {
00765 #ifdef ENABLE_NETWORK
00766   if (_network_server) NetworkAdminCompanyUpdate(company);
00767 #endif /* ENABLE_NETWORK */
00768 }
00769 
00775 void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
00776 {
00777 #ifdef ENABLE_NETWORK
00778   if (_network_server) NetworkAdminCompanyRemove(company_id, (AdminCompanyRemoveReason)reason);
00779 #endif /* ENABLE_NETWORK */
00780 }
00781 
00796 CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00797 {
00798   InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0);
00799   CompanyID company_id = (CompanyID)GB(p1, 16, 8);
00800 #ifdef ENABLE_NETWORK
00801   ClientID client_id = (ClientID)p2;
00802 #endif /* ENABLE_NETWORK */
00803 
00804   switch (GB(p1, 0, 16)) {
00805     case 0: { // Create a new company
00806       /* This command is only executed in a multiplayer game */
00807       if (!_networking) return CMD_ERROR;
00808 
00809 #ifdef ENABLE_NETWORK
00810       /* Has the network client a correct ClientIndex? */
00811       if (!(flags & DC_EXEC)) return CommandCost();
00812       NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
00813       if (ci == NULL) return CommandCost();
00814 
00815       /* Delete multiplayer progress bar */
00816       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00817 
00818       Company *c = DoStartupNewCompany(false);
00819 
00820       /* A new company could not be created, revert to being a spectator */
00821       if (c == NULL) {
00822         if (_network_server) {
00823           ci->client_playas = COMPANY_SPECTATOR;
00824           NetworkUpdateClientInfo(ci->client_id);
00825         }
00826         break;
00827       }
00828 
00829       /* This is the client (or non-dedicated server) who wants a new company */
00830       if (client_id == _network_own_client_id) {
00831         assert(_local_company == COMPANY_SPECTATOR);
00832         SetLocalCompany(c->index);
00833         if (!StrEmpty(_settings_client.network.default_company_pass)) {
00834           NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00835         }
00836 
00837         /* Now that we have a new company, broadcast our company settings to
00838          * all clients so everything is in sync */
00839         SyncCompanySettings();
00840 
00841         MarkWholeScreenDirty();
00842       }
00843 
00844       if (_network_server) {
00845         ci->client_playas = c->index;
00846         NetworkUpdateClientInfo(ci->client_id);
00847 
00848         if (Company::IsValidID(ci->client_playas)) {
00849           _network_company_states[c->index].months_empty = 0;
00850           _network_company_states[c->index].password[0] = '\0';
00851           NetworkServerUpdateCompanyPassworded(ci->client_playas, false);
00852 
00853           /* XXX - When a client joins, we automatically set its name to the
00854            * client's name (for some reason). As it stands now only the server
00855            * knows the client's name, so it needs to send out a "broadcast" to
00856            * do this. To achieve this we send a network command. However, it
00857            * uses _local_company to execute the command as.  To prevent abuse
00858            * (eg. only yourself can change your name/company), we 'cheat' by
00859            * impersonation _local_company as the server. Not the best solution;
00860            * but it works.
00861            * TODO: Perhaps this could be improved by when the client is ready
00862            * with joining to let it send itself the command, and not the server?
00863            * For example in network_client.c:534? */
00864           NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, ci->client_playas);
00865         }
00866 
00867         /* Announce new company on network. */
00868         NetworkAdminCompanyInfo(c, true);
00869         NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, ci->client_playas + 1);
00870       }
00871 #endif /* ENABLE_NETWORK */
00872       break;
00873     }
00874 
00875     case 1: // Make a new AI company
00876       if (!(flags & DC_EXEC)) return CommandCost();
00877 
00878       if (company_id != INVALID_COMPANY && (company_id >= MAX_COMPANIES || Company::IsValidID(company_id))) return CMD_ERROR;
00879       DoStartupNewCompany(true, company_id);
00880       break;
00881 
00882     case 2: { // Delete a company
00883       CompanyRemoveReason reason = (CompanyRemoveReason)GB(p2, 0, 2);
00884       if (reason >= CRR_END) return CMD_ERROR;
00885 
00886       Company *c = Company::GetIfValid(company_id);
00887       if (c == NULL) return CMD_ERROR;
00888 
00889       if (!(flags & DC_EXEC)) return CommandCost();
00890 
00891       /* Delete any open window of the company */
00892       DeleteCompanyWindows(c->index);
00893       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00894       cni->FillData(c);
00895 
00896       /* Show the bankrupt news */
00897       SetDParam(0, STR_NEWS_COMPANY_BANKRUPT_TITLE);
00898       SetDParam(1, STR_NEWS_COMPANY_BANKRUPT_DESCRIPTION);
00899       SetDParamStr(2, cni->company_name);
00900       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_BANKRUPT, cni);
00901 
00902       /* Remove the company */
00903       ChangeOwnershipOfCompanyItems(c->index, INVALID_OWNER);
00904       if (c->is_ai) AI::Stop(c->index);
00905 
00906       CompanyID c_index = c->index;
00907       delete c;
00908       AI::BroadcastNewEvent(new ScriptEventCompanyBankrupt(c_index));
00909       Game::NewEvent(new ScriptEventCompanyBankrupt(c_index));
00910       CompanyAdminRemove(c_index, (CompanyRemoveReason)reason);
00911       break;
00912     }
00913 
00914     default: return CMD_ERROR;
00915   }
00916 
00917   InvalidateWindowClassesData(WC_GAME_OPTIONS);
00918   InvalidateWindowClassesData(WC_AI_SETTINGS);
00919   InvalidateWindowClassesData(WC_AI_LIST);
00920 
00921   return CommandCost();
00922 }
00923 
00933 CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00934 {
00935   CompanyManagerFace cmf = (CompanyManagerFace)p2;
00936 
00937   if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
00938 
00939   if (flags & DC_EXEC) {
00940     Company::Get(_current_company)->face = cmf;
00941     MarkWholeScreenDirty();
00942   }
00943   return CommandCost();
00944 }
00945 
00957 CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00958 {
00959   Colours colour = Extract<Colours, 0, 4>(p2);
00960   LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
00961   byte state = GB(p1, 8, 2);
00962 
00963   if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;
00964 
00965   Company *c = Company::Get(_current_company);
00966 
00967   /* Ensure no two companies have the same primary colour */
00968   if (scheme == LS_DEFAULT && state == 0) {
00969     const Company *cc;
00970     FOR_ALL_COMPANIES(cc) {
00971       if (cc != c && cc->colour == colour) return CMD_ERROR;
00972     }
00973   }
00974 
00975   if (flags & DC_EXEC) {
00976     switch (state) {
00977       case 0:
00978         c->livery[scheme].colour1 = colour;
00979 
00980         /* If setting the first colour of the default scheme, adjust the
00981          * original and cached company colours too. */
00982         if (scheme == LS_DEFAULT) {
00983           _company_colours[_current_company] = colour;
00984           c->colour = colour;
00985           CompanyAdminUpdate(c);
00986         }
00987         break;
00988 
00989       case 1:
00990         c->livery[scheme].colour2 = colour;
00991         break;
00992 
00993       case 2:
00994         c->livery[scheme].in_use = colour != 0;
00995 
00996         /* Now handle setting the default scheme's in_use flag.
00997          * This is different to the other schemes, as it signifies if any
00998          * scheme is active at all. If this flag is not set, then no
00999          * processing of vehicle types occurs at all, and only the default
01000          * colours will be used. */
01001 
01002         /* If enabling a scheme, set the default scheme to be in use too */
01003         if (colour != 0) {
01004           c->livery[LS_DEFAULT].in_use = true;
01005           break;
01006         }
01007 
01008         /* Else loop through all schemes to see if any are left enabled.
01009          * If not, disable the default scheme too. */
01010         c->livery[LS_DEFAULT].in_use = false;
01011         for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
01012           if (c->livery[scheme].in_use) {
01013             c->livery[LS_DEFAULT].in_use = true;
01014             break;
01015           }
01016         }
01017         break;
01018 
01019       default:
01020         break;
01021     }
01022     ResetVehicleColourMap();
01023     MarkWholeScreenDirty();
01024 
01025     /* All graph related to companies use the company colour. */
01026     InvalidateWindowData(WC_INCOME_GRAPH, 0);
01027     InvalidateWindowData(WC_OPERATING_PROFIT, 0);
01028     InvalidateWindowData(WC_DELIVERED_CARGO, 0);
01029     InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
01030     InvalidateWindowData(WC_COMPANY_VALUE, 0);
01031     /* The smallmap owner view also stores the company colours. */
01032     BuildOwnerLegend();
01033     InvalidateWindowData(WC_SMALLMAP, 0, 1);
01034 
01035     /* Company colour data is indirectly cached. */
01036     Vehicle *v;
01037     FOR_ALL_VEHICLES(v) {
01038       if (v->owner == _current_company) v->InvalidateNewGRFCache();
01039     }
01040 
01041     extern void UpdateObjectColours(const Company *c);
01042     UpdateObjectColours(c);
01043   }
01044   return CommandCost();
01045 }
01046 
01052 static bool IsUniqueCompanyName(const char *name)
01053 {
01054   const Company *c;
01055 
01056   FOR_ALL_COMPANIES(c) {
01057     if (c->name != NULL && strcmp(c->name, name) == 0) return false;
01058   }
01059 
01060   return true;
01061 }
01062 
01072 CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01073 {
01074   bool reset = StrEmpty(text);
01075 
01076   if (!reset) {
01077     if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR;
01078     if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01079   }
01080 
01081   if (flags & DC_EXEC) {
01082     Company *c = Company::Get(_current_company);
01083     free(c->name);
01084     c->name = reset ? NULL : strdup(text);
01085     MarkWholeScreenDirty();
01086     CompanyAdminUpdate(c);
01087   }
01088 
01089   return CommandCost();
01090 }
01091 
01097 static bool IsUniquePresidentName(const char *name)
01098 {
01099   const Company *c;
01100 
01101   FOR_ALL_COMPANIES(c) {
01102     if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
01103   }
01104 
01105   return true;
01106 }
01107 
01117 CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01118 {
01119   bool reset = StrEmpty(text);
01120 
01121   if (!reset) {
01122     if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR;
01123     if (!IsUniquePresidentName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
01124   }
01125 
01126   if (flags & DC_EXEC) {
01127     Company *c = Company::Get(_current_company);
01128     free(c->president_name);
01129 
01130     if (reset) {
01131       c->president_name = NULL;
01132     } else {
01133       c->president_name = strdup(text);
01134 
01135       if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
01136         char buf[80];
01137 
01138         snprintf(buf, lengthof(buf), "%s Transport", text);
01139         DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
01140       }
01141     }
01142 
01143     MarkWholeScreenDirty();
01144     CompanyAdminUpdate(c);
01145   }
01146 
01147   return CommandCost();
01148 }