company_cmd.cpp

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

Generated on Fri Jun 3 05:18:49 2011 for OpenTTD by  doxygen 1.6.1