economy.cpp

Go to the documentation of this file.
00001 /* $Id: economy.cpp 23826 2012-01-20 20:18:19Z 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_func.h"
00014 #include "command_func.h"
00015 #include "industry.h"
00016 #include "town.h"
00017 #include "news_func.h"
00018 #include "network/network.h"
00019 #include "network/network_func.h"
00020 #include "ai/ai.hpp"
00021 #include "aircraft.h"
00022 #include "newgrf_engine.h"
00023 #include "engine_base.h"
00024 #include "ground_vehicle.hpp"
00025 #include "newgrf_cargo.h"
00026 #include "newgrf_sound.h"
00027 #include "newgrf_industrytiles.h"
00028 #include "newgrf_station.h"
00029 #include "newgrf_airporttiles.h"
00030 #include "object.h"
00031 #include "strings_func.h"
00032 #include "date_func.h"
00033 #include "vehicle_func.h"
00034 #include "sound_func.h"
00035 #include "autoreplace_func.h"
00036 #include "company_gui.h"
00037 #include "signs_base.h"
00038 #include "subsidy_base.h"
00039 #include "subsidy_func.h"
00040 #include "station_base.h"
00041 #include "waypoint_base.h"
00042 #include "economy_base.h"
00043 #include "core/pool_func.hpp"
00044 #include "core/backup_type.hpp"
00045 #include "water.h"
00046 #include "game/game.hpp"
00047 
00048 #include "table/strings.h"
00049 #include "table/pricebase.h"
00050 
00051 
00052 /* Initialize the cargo payment-pool */
00053 CargoPaymentPool _cargo_payment_pool("CargoPayment");
00054 INSTANTIATE_POOL_METHODS(CargoPayment)
00055 
00056 
00067 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
00068 {
00069   return (int32)((int64)a * (int64)b >> shift);
00070 }
00071 
00072 typedef SmallVector<Industry *, 16> SmallIndustryList;
00073 
00077 const ScoreInfo _score_info[] = {
00078   {     120, 100}, // SCORE_VEHICLES
00079   {      80, 100}, // SCORE_STATIONS
00080   {   10000, 100}, // SCORE_MIN_PROFIT
00081   {   50000,  50}, // SCORE_MIN_INCOME
00082   {  100000, 100}, // SCORE_MAX_INCOME
00083   {   40000, 400}, // SCORE_DELIVERED
00084   {       8,  50}, // SCORE_CARGO
00085   {10000000,  50}, // SCORE_MONEY
00086   {  250000,  50}, // SCORE_LOAN
00087   {       0,   0}  // SCORE_TOTAL
00088 };
00089 
00090 int _score_part[MAX_COMPANIES][SCORE_END];
00091 Economy _economy;
00092 Prices _price;
00093 Money _additional_cash_required;
00094 static PriceMultipliers _price_base_multiplier;
00095 
00105 Money CalculateCompanyValue(const Company *c, bool including_loan)
00106 {
00107   Owner owner = c->index;
00108 
00109   Station *st;
00110   uint num = 0;
00111 
00112   FOR_ALL_STATIONS(st) {
00113     if (st->owner == owner) num += CountBits((byte)st->facilities);
00114   }
00115 
00116   Money value = num * _price[PR_STATION_VALUE] * 25;
00117 
00118   Vehicle *v;
00119   FOR_ALL_VEHICLES(v) {
00120     if (v->owner != owner) continue;
00121 
00122     if (v->type == VEH_TRAIN ||
00123         v->type == VEH_ROAD ||
00124         (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
00125         v->type == VEH_SHIP) {
00126       value += v->value * 3 >> 1;
00127     }
00128   }
00129 
00130   /* Add real money value */
00131   if (including_loan) value -= c->current_loan;
00132   value += c->money;
00133 
00134   return max(value, (Money)1);
00135 }
00136 
00145 int UpdateCompanyRatingAndValue(Company *c, bool update)
00146 {
00147   Owner owner = c->index;
00148   int score = 0;
00149 
00150   memset(_score_part[owner], 0, sizeof(_score_part[owner]));
00151 
00152   /* Count vehicles */
00153   {
00154     Vehicle *v;
00155     Money min_profit = 0;
00156     bool min_profit_first = true;
00157     uint num = 0;
00158 
00159     FOR_ALL_VEHICLES(v) {
00160       if (v->owner != owner) continue;
00161       if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
00162         if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
00163         if (v->age > 730) {
00164           /* Find the vehicle with the lowest amount of profit */
00165           if (min_profit_first || min_profit > v->profit_last_year) {
00166             min_profit = v->profit_last_year;
00167             min_profit_first = false;
00168           }
00169         }
00170       }
00171     }
00172 
00173     min_profit >>= 8; // remove the fract part
00174 
00175     _score_part[owner][SCORE_VEHICLES] = num;
00176     /* Don't allow negative min_profit to show */
00177     if (min_profit > 0) {
00178       _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
00179     }
00180   }
00181 
00182   /* Count stations */
00183   {
00184     uint num = 0;
00185     const Station *st;
00186 
00187     FOR_ALL_STATIONS(st) {
00188       /* Only count stations that are actually serviced */
00189       if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
00190     }
00191     _score_part[owner][SCORE_STATIONS] = num;
00192   }
00193 
00194   /* Generate statistics depending on recent income statistics */
00195   {
00196     int numec = min(c->num_valid_stat_ent, 12);
00197     if (numec != 0) {
00198       const CompanyEconomyEntry *cee = c->old_economy;
00199       Money min_income = cee->income + cee->expenses;
00200       Money max_income = cee->income + cee->expenses;
00201 
00202       do {
00203         min_income = min(min_income, cee->income + cee->expenses);
00204         max_income = max(max_income, cee->income + cee->expenses);
00205       } while (++cee, --numec);
00206 
00207       if (min_income > 0) {
00208         _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
00209       }
00210 
00211       _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
00212     }
00213   }
00214 
00215   /* Generate score depending on amount of transported cargo */
00216   {
00217     int numec = min(c->num_valid_stat_ent, 4);
00218     if (numec != 0) {
00219       const CompanyEconomyEntry *cee = c->old_economy;
00220       OverflowSafeInt64 total_delivered = 0;
00221       do {
00222         total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
00223       } while (++cee, --numec);
00224 
00225       _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
00226     }
00227   }
00228 
00229   /* Generate score for variety of cargo */
00230   {
00231     _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
00232   }
00233 
00234   /* Generate score for company's money */
00235   {
00236     if (c->money > 0) {
00237       _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
00238     }
00239   }
00240 
00241   /* Generate score for loan */
00242   {
00243     _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
00244   }
00245 
00246   /* Now we calculate the score for each item.. */
00247   {
00248     int total_score = 0;
00249     int s;
00250     score = 0;
00251     for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
00252       /* Skip the total */
00253       if (i == SCORE_TOTAL) continue;
00254       /*  Check the score */
00255       s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
00256       score += s;
00257       total_score += _score_info[i].score;
00258     }
00259 
00260     _score_part[owner][SCORE_TOTAL] = score;
00261 
00262     /*  We always want the score scaled to SCORE_MAX (1000) */
00263     if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
00264   }
00265 
00266   if (update) {
00267     c->old_economy[0].performance_history = score;
00268     UpdateCompanyHQ(c->location_of_HQ, score);
00269     c->old_economy[0].company_value = CalculateCompanyValue(c);
00270   }
00271 
00272   SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
00273   return score;
00274 }
00275 
00281 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
00282 {
00283   /* We need to set _current_company to old_owner before we try to move
00284    * the client. This is needed as it needs to know whether "you" really
00285    * are the current local company. */
00286   Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
00287 #ifdef ENABLE_NETWORK
00288   /* In all cases, make spectators of clients connected to that company */
00289   if (_networking) NetworkClientsToSpectators(old_owner);
00290 #endif /* ENABLE_NETWORK */
00291   if (old_owner == _local_company) {
00292     /* Single player cheated to AI company.
00293      * There are no specatators in single player, so we must pick some other company. */
00294     assert(!_networking);
00295     Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
00296     Company *c;
00297     FOR_ALL_COMPANIES(c) {
00298       if (c->index != old_owner) {
00299         SetLocalCompany(c->index);
00300         break;
00301       }
00302     }
00303     cur_company.Restore();
00304     assert(old_owner != _local_company);
00305   }
00306 
00307   Town *t;
00308 
00309   assert(old_owner != new_owner);
00310 
00311   {
00312     Company *c;
00313     uint i;
00314 
00315     /* See if the old_owner had shares in other companies */
00316     FOR_ALL_COMPANIES(c) {
00317       for (i = 0; i < 4; i++) {
00318         if (c->share_owners[i] == old_owner) {
00319           /* Sell his shares */
00320           CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
00321           /* Because we are in a DoCommand, we can't just execute another one and
00322            *  expect the money to be removed. We need to do it ourself! */
00323           SubtractMoneyFromCompany(res);
00324         }
00325       }
00326     }
00327 
00328     /* Sell all the shares that people have on this company */
00329     Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
00330     c = Company::Get(old_owner);
00331     for (i = 0; i < 4; i++) {
00332       cur_company2.Change(c->share_owners[i]);
00333       if (_current_company != INVALID_OWNER) {
00334         /* Sell the shares */
00335         CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
00336         /* Because we are in a DoCommand, we can't just execute another one and
00337          *  expect the money to be removed. We need to do it ourself! */
00338         SubtractMoneyFromCompany(res);
00339       }
00340     }
00341     cur_company2.Restore();
00342   }
00343 
00344   /* Temporarily increase the company's money, to be sure that
00345    * removing his/her property doesn't fail because of lack of money.
00346    * Not too drastically though, because it could overflow */
00347   if (new_owner == INVALID_OWNER) {
00348     Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
00349   }
00350 
00351   Subsidy *s;
00352   FOR_ALL_SUBSIDIES(s) {
00353     if (s->awarded == old_owner) {
00354       if (new_owner == INVALID_OWNER) {
00355         delete s;
00356       } else {
00357         s->awarded = new_owner;
00358       }
00359     }
00360   }
00361   if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
00362 
00363   /* Take care of rating in towns */
00364   FOR_ALL_TOWNS(t) {
00365     /* If a company takes over, give the ratings to that company. */
00366     if (new_owner != INVALID_OWNER) {
00367       if (HasBit(t->have_ratings, old_owner)) {
00368         if (HasBit(t->have_ratings, new_owner)) {
00369           /* use max of the two ratings. */
00370           t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
00371         } else {
00372           SetBit(t->have_ratings, new_owner);
00373           t->ratings[new_owner] = t->ratings[old_owner];
00374         }
00375       }
00376     }
00377 
00378     /* Reset the ratings for the old owner */
00379     t->ratings[old_owner] = RATING_INITIAL;
00380     ClrBit(t->have_ratings, old_owner);
00381   }
00382 
00383   {
00384     Vehicle *v;
00385     FOR_ALL_VEHICLES(v) {
00386       if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
00387         if (new_owner == INVALID_OWNER) {
00388           if (v->Previous() == NULL) delete v;
00389         } else {
00390           if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
00391           if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
00392         }
00393       }
00394     }
00395   }
00396 
00397   /* In all cases clear replace engine rules.
00398    * Even if it was copied, it could interfere with new owner's rules */
00399   RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
00400 
00401   if (new_owner == INVALID_OWNER) {
00402     RemoveAllGroupsForCompany(old_owner);
00403   } else {
00404     Group *g;
00405     FOR_ALL_GROUPS(g) {
00406       if (g->owner == old_owner) g->owner = new_owner;
00407     }
00408   }
00409 
00410   {
00411     FreeUnitIDGenerator unitidgen[] = {
00412       FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD,     new_owner),
00413       FreeUnitIDGenerator(VEH_SHIP,  new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
00414     };
00415 
00416     Vehicle *v;
00417     FOR_ALL_VEHICLES(v) {
00418       if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
00419         assert(new_owner != INVALID_OWNER);
00420 
00421         v->owner = new_owner;
00422         v->colourmap = PAL_NONE;
00423 
00424         if (v->IsEngineCountable()) {
00425           GroupStatistics::CountEngine(v, 1);
00426         }
00427         if (v->IsPrimaryVehicle()) {
00428           GroupStatistics::CountVehicle(v, 1);
00429           v->unitnumber = unitidgen[v->type].NextID();
00430         }
00431 
00432         /* Invalidate the vehicle's cargo payment "owner cache". */
00433         if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
00434       }
00435     }
00436 
00437     if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
00438   }
00439 
00440   /*  Change ownership of tiles */
00441   {
00442     TileIndex tile = 0;
00443     do {
00444       ChangeTileOwner(tile, old_owner, new_owner);
00445     } while (++tile != MapSize());
00446 
00447     if (new_owner != INVALID_OWNER) {
00448       /* Update all signals because there can be new segment that was owned by two companies
00449        * and signals were not propagated
00450        * Similiar with crossings - it is needed to bar crossings that weren't before
00451        * because of different owner of crossing and approaching train */
00452       tile = 0;
00453 
00454       do {
00455         if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
00456           TrackBits tracks = GetTrackBits(tile);
00457           do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
00458             Track track = RemoveFirstTrack(&tracks);
00459             if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
00460           } while (tracks != TRACK_BIT_NONE);
00461         } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
00462           UpdateLevelCrossing(tile);
00463         }
00464       } while (++tile != MapSize());
00465     }
00466 
00467     /* update signals in buffer */
00468     UpdateSignalsInBuffer();
00469   }
00470 
00471   /* convert owner of stations (including deleted ones, but excluding buoys) */
00472   Station *st;
00473   FOR_ALL_STATIONS(st) {
00474     if (st->owner == old_owner) {
00475       /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
00476        * also, drawing station window would cause reading invalid company's colour */
00477       st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
00478     }
00479   }
00480 
00481   /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
00482   Waypoint *wp;
00483   FOR_ALL_WAYPOINTS(wp) {
00484     if (wp->owner == old_owner) {
00485       wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
00486     }
00487   }
00488 
00489   Sign *si;
00490   FOR_ALL_SIGNS(si) {
00491     if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
00492   }
00493 
00494   /* Change colour of existing windows */
00495   if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
00496 
00497   cur_company.Restore();
00498 
00499   MarkWholeScreenDirty();
00500 }
00501 
00506 static void CompanyCheckBankrupt(Company *c)
00507 {
00508   /*  If the company has money again, it does not go bankrupt */
00509   if (c->money >= 0) {
00510     c->quarters_of_bankruptcy = 0;
00511     c->bankrupt_asked = 0;
00512     return;
00513   }
00514 
00515   c->quarters_of_bankruptcy++;
00516 
00517   switch (c->quarters_of_bankruptcy) {
00518     case 0:
00519     case 1:
00520       break;
00521 
00522     case 2: {
00523       CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
00524       cni->FillData(c);
00525       SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
00526       SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
00527       SetDParamStr(2, cni->company_name);
00528       AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_TROUBLE, cni);
00529       AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
00530       Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
00531       break;
00532     }
00533 
00534     case 3: {
00535       /* Check if the company has any value.. if not, declare it bankrupt
00536        *  right now */
00537       Money val = CalculateCompanyValue(c, false);
00538       if (val > 0) {
00539         c->bankrupt_value = val;
00540         c->bankrupt_asked = 1 << c->index; // Don't ask the owner
00541         c->bankrupt_timeout = 0;
00542         break;
00543       }
00544       /* FALL THROUGH to case 4... */
00545     }
00546     default:
00547     case 4:
00548       if (!_networking && _local_company == c->index) {
00549         /* If we are in offline mode, leave the company playing. Eg. there
00550          * is no THE-END, otherwise mark the client as spectator to make sure
00551          * he/she is no long in control of this company. However... when you
00552          * join another company (cheat) the "unowned" company can bankrupt. */
00553         c->bankrupt_asked = MAX_UVALUE(CompanyMask);
00554         break;
00555       }
00556 
00557       /* Actually remove the company, but not when we're a network client.
00558        * In case of network clients we will be getting a command from the
00559        * server. It is done in this way as we are called from the
00560        * StateGameLoop which can't change the current company, and thus
00561        * updating the local company triggers an assert later on. In the
00562        * case of a network game the command will be processed at a time
00563        * that changing the current company is okay. In case of single
00564        * player we are sure (the above check) that we are not the local
00565        * company and thus we won't be moved. */
00566       if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
00567       break;
00568   }
00569 }
00570 
00575 static void CompaniesGenStatistics()
00576 {
00577   Station *st;
00578 
00579   Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
00580   Company *c;
00581 
00582   if (!_settings_game.economy.infrastructure_maintenance) {
00583     FOR_ALL_STATIONS(st) {
00584       cur_company.Change(st->owner);
00585       CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
00586       SubtractMoneyFromCompany(cost);
00587     }
00588   } else {
00589     /* Improved monthly infrastructure costs. */
00590     FOR_ALL_COMPANIES(c) {
00591       cur_company.Change(c->index);
00592 
00593       CommandCost cost(EXPENSES_PROPERTY);
00594       for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
00595         if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt]));
00596       }
00597       cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
00598       for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
00599         if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
00600       }
00601       cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
00602       cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
00603       cost.AddCost(AirportMaintenanceCost(c->index));
00604 
00605       SubtractMoneyFromCompany(cost);
00606     }
00607   }
00608   cur_company.Restore();
00609 
00610   /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
00611   if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
00612 
00613   FOR_ALL_COMPANIES(c) {
00614     memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
00615     c->old_economy[0] = c->cur_economy;
00616     memset(&c->cur_economy, 0, sizeof(c->cur_economy));
00617 
00618     if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
00619 
00620     UpdateCompanyRatingAndValue(c, true);
00621     if (c->block_preview != 0) c->block_preview--;
00622     CompanyCheckBankrupt(c);
00623   }
00624 
00625   SetWindowDirty(WC_INCOME_GRAPH, 0);
00626   SetWindowDirty(WC_OPERATING_PROFIT, 0);
00627   SetWindowDirty(WC_DELIVERED_CARGO, 0);
00628   SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
00629   SetWindowDirty(WC_COMPANY_VALUE, 0);
00630   SetWindowDirty(WC_COMPANY_LEAGUE, 0);
00631 }
00632 
00637 void AddInflation(bool check_year)
00638 {
00639   /* The cargo payment inflation differs from the normal inflation, so the
00640    * relative amount of money you make with a transport decreases slowly over
00641    * the 170 years. After a few hundred years we reach a level in which the
00642    * games will become unplayable as the maximum income will be less than
00643    * the minimum running cost.
00644    *
00645    * Furthermore there are a lot of inflation related overflows all over the
00646    * place. Solving them is hardly possible because inflation will always
00647    * reach the overflow threshold some day. So we'll just perform the
00648    * inflation mechanism during the first 170 years (the amount of years that
00649    * one had in the original TTD) and stop doing the inflation after that
00650    * because it only causes problems that can't be solved nicely and the
00651    * inflation doesn't add anything after that either; it even makes playing
00652    * it impossible due to the diverging cost and income rates.
00653    */
00654   if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return;
00655 
00656   /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
00657    * scaled by 65536
00658    * 12 -> months per year
00659    * This is only a good approxiamtion for small values
00660    */
00661   _economy.inflation_prices  += min((_economy.inflation_prices  * _economy.infl_amount    * 54) >> 16, MAX_INFLATION);
00662   _economy.inflation_payment += min((_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16, MAX_INFLATION);
00663 }
00664 
00668 void RecomputePrices()
00669 {
00670   /* Setup maximum loan */
00671   _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
00672 
00673   /* Setup price bases */
00674   for (Price i = PR_BEGIN; i < PR_END; i++) {
00675     Money price = _price_base_specs[i].start_price;
00676 
00677     /* Apply difficulty settings */
00678     uint mod = 1;
00679     switch (_price_base_specs[i].category) {
00680       case PCAT_RUNNING:
00681         mod = _settings_game.difficulty.vehicle_costs;
00682         break;
00683 
00684       case PCAT_CONSTRUCTION:
00685         mod = _settings_game.difficulty.construction_cost;
00686         break;
00687 
00688       default: break;
00689     }
00690     switch (mod) {
00691       case 0: price *= 6; break;
00692       case 1: price *= 8; break; // normalised to 1 below
00693       case 2: price *= 9; break;
00694       default: NOT_REACHED();
00695     }
00696 
00697     /* Apply inflation */
00698     price = (int64)price * _economy.inflation_prices;
00699 
00700     /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
00701     int shift = _price_base_multiplier[i] - 16 - 3;
00702     if (shift >= 0) {
00703       price <<= shift;
00704     } else {
00705       price >>= -shift;
00706     }
00707 
00708     /* Make sure the price does not get reduced to zero.
00709      * Zero breaks quite a few commands that use a zero
00710      * cost to see whether something got changed or not
00711      * and based on that cause an error. When the price
00712      * is zero that fails even when things are done. */
00713     if (price == 0) {
00714       price = Clamp(_price_base_specs[i].start_price, -1, 1);
00715       /* No base price should be zero, but be sure. */
00716       assert(price != 0);
00717     }
00718     /* Store value */
00719     _price[i] = price;
00720   }
00721 
00722   /* Setup cargo payment */
00723   CargoSpec *cs;
00724   FOR_ALL_CARGOSPECS(cs) {
00725     cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
00726   }
00727 
00728   SetWindowClassesDirty(WC_BUILD_VEHICLE);
00729   SetWindowClassesDirty(WC_REPLACE_VEHICLE);
00730   SetWindowClassesDirty(WC_VEHICLE_DETAILS);
00731   SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
00732   InvalidateWindowData(WC_PAYMENT_RATES, 0);
00733 }
00734 
00736 static void CompaniesPayInterest()
00737 {
00738   const Company *c;
00739 
00740   Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
00741   FOR_ALL_COMPANIES(c) {
00742     cur_company.Change(c->index);
00743 
00744     /* Over a year the paid interest should be "loan * interest percentage",
00745      * but... as that number is likely not dividable by 12 (pay each month),
00746      * one needs to account for that in the monthly fee calculations.
00747      * To easily calculate what one should pay "this" month, you calculate
00748      * what (total) should have been paid up to this month and you subtract
00749      * whatever has been paid in the previous months. This will mean one month
00750      * it'll be a bit more and the other it'll be a bit less than the average
00751      * monthly fee, but on average it will be exact. */
00752     Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
00753     Money up_to_previous_month = yearly_fee * _cur_month / 12;
00754     Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
00755 
00756     SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
00757 
00758     SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
00759   }
00760   cur_company.Restore();
00761 }
00762 
00763 static void HandleEconomyFluctuations()
00764 {
00765   if (_settings_game.difficulty.economy != 0) {
00766     /* When economy is Fluctuating, decrease counter */
00767     _economy.fluct--;
00768   } else if (EconomyIsInRecession()) {
00769     /* When it's Steady and we are in recession, end it now */
00770     _economy.fluct = -12;
00771   } else {
00772     /* No need to do anything else in other cases */
00773     return;
00774   }
00775 
00776   if (_economy.fluct == 0) {
00777     _economy.fluct = -(int)GB(Random(), 0, 2);
00778     AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NS_ECONOMY);
00779   } else if (_economy.fluct == -12) {
00780     _economy.fluct = GB(Random(), 0, 8) + 312;
00781     AddNewsItem(STR_NEWS_END_OF_RECESSION, NS_ECONOMY);
00782   }
00783 }
00784 
00785 
00789 void ResetPriceBaseMultipliers()
00790 {
00791   memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
00792 }
00793 
00801 void SetPriceBaseMultiplier(Price price, int factor)
00802 {
00803   assert(price < PR_END);
00804   _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
00805 }
00806 
00811 void StartupIndustryDailyChanges(bool init_counter)
00812 {
00813   uint map_size = MapLogX() + MapLogY();
00814   /* After getting map size, it needs to be scaled appropriately and divided by 31,
00815    * which stands for the days in a month.
00816    * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
00817    * would not be needed.
00818    * Since it is based on "fractionnal parts", the leftover days will not make much of a difference
00819    * on the overall total number of changes performed */
00820   _economy.industry_daily_increment = (1 << map_size) / 31;
00821 
00822   if (init_counter) {
00823     /* A new game or a savegame from an older version will require the counter to be initialized */
00824     _economy.industry_daily_change_counter = 0;
00825   }
00826 }
00827 
00828 void StartupEconomy()
00829 {
00830   _economy.interest_rate = _settings_game.difficulty.initial_interest;
00831   _economy.infl_amount = _settings_game.difficulty.initial_interest;
00832   _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
00833   _economy.fluct = GB(Random(), 0, 8) + 168;
00834 
00835   /* Set up prices */
00836   RecomputePrices();
00837 
00838   StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
00839 
00840 }
00841 
00845 void InitializeEconomy()
00846 {
00847   _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
00848 }
00849 
00858 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
00859 {
00860   if (index >= PR_END) return 0;
00861 
00862   Money cost = _price[index] * cost_factor;
00863   if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
00864 
00865   if (shift >= 0) {
00866     cost <<= shift;
00867   } else {
00868     cost >>= -shift;
00869   }
00870 
00871   return cost;
00872 }
00873 
00874 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
00875 {
00876   const CargoSpec *cs = CargoSpec::Get(cargo_type);
00877   if (!cs->IsValid()) {
00878     /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
00879     return 0;
00880   }
00881 
00882   /* Use callback to calculate cargo profit, if available */
00883   if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
00884     uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
00885     uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
00886     if (callback != CALLBACK_FAILED) {
00887       int result = GB(callback, 0, 14);
00888 
00889       /* Simulate a 15 bit signed value */
00890       if (HasBit(callback, 14)) result -= 0x4000;
00891 
00892       /* "The result should be a signed multiplier that gets multiplied
00893        * by the amount of cargo moved and the price factor, then gets
00894        * divided by 8192." */
00895       return result * num_pieces * cs->current_payment / 8192;
00896     }
00897   }
00898 
00899   static const int MIN_TIME_FACTOR = 31;
00900   static const int MAX_TIME_FACTOR = 255;
00901 
00902   const int days1 = cs->transit_days[0];
00903   const int days2 = cs->transit_days[1];
00904   const int days_over_days1 = max(   transit_days - days1, 0);
00905   const int days_over_days2 = max(days_over_days1 - days2, 0);
00906 
00907   /*
00908    * The time factor is calculated based on the time it took
00909    * (transit_days) compared two cargo-depending values. The
00910    * range is divided into three parts:
00911    *
00912    *  - constant for fast transits
00913    *  - linear decreasing with time with a slope of -1 for medium transports
00914    *  - linear decreasing with time with a slope of -2 for slow transports
00915    *
00916    */
00917   const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
00918 
00919   return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
00920 }
00921 
00923 static SmallIndustryList _cargo_delivery_destinations;
00924 
00934 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
00935 {
00936   /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
00937    * This fails in three cases:
00938    *  1) The station accepts the cargo because there are enough houses around it accepting the cargo.
00939    *  2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
00940    *  3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
00941    */
00942 
00943   uint accepted = 0;
00944 
00945   for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) {
00946     Industry *ind = st->industries_near[i];
00947     if (ind->index == source) continue;
00948 
00949     uint cargo_index;
00950     for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
00951       if (cargo_type == ind->accepts_cargo[cargo_index]) break;
00952     }
00953     /* Check if matching cargo has been found */
00954     if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
00955 
00956     /* Check if industry temporarily refuses acceptance */
00957     if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
00958 
00959     /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
00960     _cargo_delivery_destinations.Include(ind);
00961 
00962     uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
00963     ind->incoming_cargo_waiting[cargo_index] += amount;
00964     num_pieces -= amount;
00965     accepted += amount;
00966   }
00967 
00968   return accepted;
00969 }
00970 
00984 static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
00985 {
00986   assert(num_pieces > 0);
00987 
00988   Station *st = Station::Get(dest);
00989 
00990   /* Give the goods to the industry. */
00991   uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY);
00992 
00993   /* If this cargo type is always accepted, accept all */
00994   if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
00995 
00996   /* Update station statistics */
00997   if (accepted > 0) {
00998     SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_EVER_ACCEPTED);
00999     SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_CURRENT_MONTH);
01000     SetBit(st->goods[cargo_type].acceptance_pickup, GoodsEntry::GES_ACCEPTED_BIGTICK);
01001   }
01002 
01003   /* Update company statistics */
01004   company->cur_economy.delivered_cargo[cargo_type] += accepted;
01005 
01006   /* Increase town's counter for town effects */
01007   const CargoSpec *cs = CargoSpec::Get(cargo_type);
01008   st->town->received[cs->town_effect].new_act += accepted;
01009 
01010   /* Determine profit */
01011   Money profit = GetTransportedGoodsIncome(accepted, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
01012 
01013   /* Modify profit if a subsidy is in effect */
01014   if (CheckSubsidised(cargo_type, company->index, src_type, src, st))  {
01015     switch (_settings_game.difficulty.subsidy_multiplier) {
01016       case 0:  profit += profit >> 1; break;
01017       case 1:  profit *= 2; break;
01018       case 2:  profit *= 3; break;
01019       default: profit *= 4; break;
01020     }
01021   }
01022 
01023   return profit;
01024 }
01025 
01031 static void TriggerIndustryProduction(Industry *i)
01032 {
01033   const IndustrySpec *indspec = GetIndustrySpec(i->type);
01034   uint16 callback = indspec->callback_mask;
01035 
01036   i->was_cargo_delivered = true;
01037   i->last_cargo_accepted_at = _date;
01038 
01039   if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
01040     if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
01041       IndustryProductionCallback(i, 0);
01042     } else {
01043       SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
01044     }
01045   } else {
01046     for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
01047       uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
01048       if (cargo_waiting == 0) continue;
01049 
01050       i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
01051       i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
01052 
01053       i->incoming_cargo_waiting[cargo_index] = 0;
01054     }
01055   }
01056 
01057   TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
01058   StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
01059 }
01060 
01065 CargoPayment::CargoPayment(Vehicle *front) :
01066   front(front),
01067   current_station(front->last_station_visited)
01068 {
01069 }
01070 
01071 CargoPayment::~CargoPayment()
01072 {
01073   if (this->CleaningPool()) return;
01074 
01075   this->front->cargo_payment = NULL;
01076 
01077   if (this->visual_profit == 0) return;
01078 
01079   Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
01080 
01081   SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
01082   this->front->profit_this_year += this->visual_profit << 8;
01083 
01084   if (this->route_profit != 0) {
01085     if (IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
01086       SndPlayVehicleFx(SND_14_CASHTILL, this->front);
01087     }
01088 
01089     ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, -this->visual_profit);
01090   } else {
01091     ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, this->visual_profit);
01092   }
01093 
01094   cur_company.Restore();
01095 }
01096 
01102 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
01103 {
01104   if (this->owner == NULL) {
01105     this->owner = Company::Get(this->front->owner);
01106   }
01107 
01108   /* Handle end of route payment */
01109   Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
01110   this->route_profit += profit;
01111 
01112   /* The vehicle's profit is whatever route profit there is minus feeder shares. */
01113   this->visual_profit += profit - cp->FeederShare();
01114 }
01115 
01122 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
01123 {
01124   Money profit = GetTransportedGoodsIncome(
01125       count,
01126       /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
01127       DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy),
01128       cp->DaysInTransit(),
01129       this->ct);
01130 
01131   profit = profit * _settings_game.economy.feeder_payment_share / 100;
01132 
01133   this->visual_profit += profit; // accumulate transfer profits for whole vehicle
01134   return profit; // account for the (virtual) profit already made for the cargo packet
01135 }
01136 
01141 void PrepareUnload(Vehicle *front_v)
01142 {
01143   /* At this moment loading cannot be finished */
01144   ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
01145 
01146   /* Start unloading in at the first possible moment */
01147   front_v->load_unload_ticks = 1;
01148 
01149   if ((front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
01150     for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
01151       if (v->cargo_cap > 0 && !v->cargo.Empty()) {
01152         SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
01153       }
01154     }
01155   }
01156 
01157   assert(front_v->cargo_payment == NULL);
01158   /* One CargoPayment per vehicle and the vehicle limit equals the
01159    * limit in number of CargoPayments. Can't go wrong. */
01160   assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
01161   assert(CargoPayment::CanAllocateItem());
01162   front_v->cargo_payment = new CargoPayment(front_v);
01163 }
01164 
01170 static bool IsArticulatedVehicleEmpty(Vehicle *v)
01171 {
01172   v = v->GetFirstEnginePart();
01173 
01174   for (; v != NULL; v = v->HasArticulatedPart() ? v->GetNextArticulatedPart() : NULL) {
01175     if (v->cargo.Count() != 0) return false;
01176   }
01177 
01178   return true;
01179 }
01180 
01189 static void LoadUnloadVehicle(Vehicle *front, int *cargo_left)
01190 {
01191   assert(front->current_order.IsType(OT_LOADING));
01192 
01193   /* We have not waited enough time till the next round of loading/unloading */
01194   if (front->load_unload_ticks != 0) {
01195     if (_settings_game.order.improved_load && (front->current_order.GetLoadType() & OLFB_FULL_LOAD)) {
01196       /* 'Reserve' this cargo for this vehicle, because we were first. */
01197       for (Vehicle *v = front; v != NULL; v = v->Next()) {
01198         int cap_left = v->cargo_cap - v->cargo.Count();
01199         if (cap_left > 0) cargo_left[v->cargo_type] -= cap_left;
01200       }
01201     }
01202     return;
01203   }
01204 
01205   StationID last_visited = front->last_station_visited;
01206   Station *st = Station::Get(last_visited);
01207 
01208   if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
01209     /* The train reversed in the station. Take the "easy" way
01210      * out and let the train just leave as it always did. */
01211     SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
01212     front->load_unload_ticks = 1;
01213     return;
01214   }
01215 
01216   int unloading_time = 0;
01217   bool dirty_vehicle = false;
01218   bool dirty_station = false;
01219 
01220   bool completely_emptied = true;
01221   bool anything_unloaded = false;
01222   bool anything_loaded   = false;
01223   uint32 full_load_amount = 0;
01224   uint32 cargo_not_full  = 0;
01225   uint32 cargo_full      = 0;
01226 
01227   front->cur_speed = 0;
01228 
01229   CargoPayment *payment = front->cargo_payment;
01230 
01231   uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
01232   for (Vehicle *v = front; v != NULL; v = v->Next()) {
01233     if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
01234     if (v->cargo_cap == 0) continue;
01235     artic_part++;
01236 
01237     const Engine *e = v->GetEngine();
01238     byte load_amount = e->info.load_amount;
01239 
01240     /* The default loadamount for mail is 1/4 of the load amount for passengers */
01241     if (v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft()) load_amount = CeilDiv(load_amount, 4);
01242 
01243     if (_settings_game.order.gradual_loading) {
01244       uint16 cb_load_amount = CALLBACK_FAILED;
01245       if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
01246         /* Use callback 36 */
01247         cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
01248       } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
01249         /* Use callback 12 */
01250         cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
01251       }
01252       if (cb_load_amount != CALLBACK_FAILED) {
01253         if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
01254         if (cb_load_amount >= 0x100) {
01255           ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
01256         } else if (cb_load_amount != 0) {
01257           load_amount = cb_load_amount;
01258         }
01259       }
01260     }
01261 
01262     GoodsEntry *ge = &st->goods[v->cargo_type];
01263 
01264     if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
01265       uint cargo_count = v->cargo.Count();
01266       uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, load_amount) : cargo_count;
01267       bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
01268       bool accepted  = false; // Is the cargo accepted by the station?
01269 
01270       payment->SetCargo(v->cargo_type);
01271 
01272       if (HasBit(ge->acceptance_pickup, GoodsEntry::GES_ACCEPTANCE) && !(front->current_order.GetUnloadType() & OUFB_TRANSFER)) {
01273         /* The cargo has reached its final destination, the packets may now be destroyed */
01274         remaining = v->cargo.MoveTo<StationCargoList>(NULL, amount_unloaded, VehicleCargoList::MTA_FINAL_DELIVERY, payment, last_visited);
01275 
01276         dirty_vehicle = true;
01277         accepted = true;
01278       }
01279 
01280       /* The !accepted || v->cargo.Count == cargo_count clause is there
01281        * to make it possible to force unload vehicles at the station where
01282        * they were loaded, but to not force unload the vehicle when the
01283        * station is still accepting the cargo in the vehicle. It doesn't
01284        * accept cargo that was loaded at the same station. */
01285       if ((front->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) && (!accepted || v->cargo.Count() == cargo_count)) {
01286         remaining = v->cargo.MoveTo(&ge->cargo, amount_unloaded, front->current_order.GetUnloadType() & OUFB_TRANSFER ? VehicleCargoList::MTA_TRANSFER : VehicleCargoList::MTA_UNLOAD, payment);
01287         if (!HasBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP)) {
01288           InvalidateWindowData(WC_STATION_LIST, last_visited);
01289           SetBit(ge->acceptance_pickup, GoodsEntry::GES_PICKUP);
01290         }
01291 
01292         dirty_vehicle = dirty_station = true;
01293       } else if (!accepted) {
01294         /* The order changed while unloading (unset unload/transfer) or the
01295          * station does not accept our goods. */
01296         ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
01297 
01298         /* Say we loaded something, otherwise we'll think we didn't unload
01299          * something and we didn't load something, so we must be finished
01300          * at this station. Setting the unloaded means that we will get a
01301          * retry for loading in the next cycle. */
01302         anything_unloaded = true;
01303         continue;
01304       }
01305 
01306       /* Deliver goods to the station */
01307       st->time_since_unload = 0;
01308 
01309       unloading_time += amount_unloaded;
01310 
01311       anything_unloaded = true;
01312       if (_settings_game.order.gradual_loading && remaining) {
01313         completely_emptied = false;
01314       } else {
01315         /* We have finished unloading (cargo count == 0) */
01316         ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
01317       }
01318 
01319       continue;
01320     }
01321 
01322     /* Do not pick up goods when we have no-load set or loading is stopped. */
01323     if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
01324 
01325     /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
01326     if (front->current_order.IsRefit() && artic_part == 1 && IsArticulatedVehicleEmpty(v) &&
01327         (v->type != VEH_AIRCRAFT || (Aircraft::From(v)->IsNormalAircraft() && v->Next()->cargo.Count() == 0))) {
01328       Vehicle *v_start = v->GetFirstEnginePart();
01329       CargoID new_cid = front->current_order.GetRefitCargo();
01330       byte new_subtype = front->current_order.GetRefitSubtype();
01331 
01332       Backup<CompanyByte> cur_company(_current_company, front->owner, FILE_LINE);
01333 
01334       /* Check if all articulated parts are empty and collect refit mask. */
01335       uint32 refit_mask = e->info.refit_mask;
01336       Vehicle *w = v_start;
01337       while (w->HasArticulatedPart()) {
01338         w = w->GetNextArticulatedPart();
01339         if (w->cargo.Count() > 0) new_cid = CT_NO_REFIT;
01340         refit_mask |= EngInfo(w->engine_type)->refit_mask;
01341       }
01342 
01343       if (new_cid == CT_AUTO_REFIT) {
01344         /* Get refittable cargo type with the most waiting cargo. */
01345         int amount = 0;
01346         CargoID cid;
01347         FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
01348           if (cargo_left[cid] > amount) {
01349             /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
01350              * the returned refit capacity will be greater than zero. */
01351             new_subtype = GetBestFittingSubType(v, v, cid);
01352             DoCommand(v_start->tile, v_start->index, cid | 1U << 6 | new_subtype << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
01353             if (_returned_refit_capacity > 0) {
01354               amount = cargo_left[cid];
01355               new_cid = cid;
01356             }
01357           }
01358         }
01359       }
01360 
01361       /* Refit if given a valid cargo. */
01362       if (new_cid < NUM_CARGO) {
01363         CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 6 | new_subtype << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
01364         if (cost.Succeeded()) front->profit_this_year -= cost.GetCost() << 8;
01365         ge = &st->goods[v->cargo_type];
01366       }
01367 
01368       cur_company.Restore();
01369     }
01370 
01371     /* update stats */
01372     int t;
01373     switch (front->type) {
01374       case VEH_TRAIN: /* FALL THROUGH */
01375       case VEH_SHIP:
01376         t = front->vcache.cached_max_speed;
01377         break;
01378 
01379       case VEH_ROAD:
01380         t = front->vcache.cached_max_speed / 2;
01381         break;
01382 
01383       case VEH_AIRCRAFT:
01384         t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
01385         break;
01386 
01387       default: NOT_REACHED();
01388     }
01389 
01390     /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
01391     ge->last_speed = min(t, 255);
01392     ge->last_age = _cur_year - front->build_year;
01393     ge->days_since_pickup = 0;
01394 
01395     /* If there's goods waiting at the station, and the vehicle
01396      * has capacity for it, load it on the vehicle. */
01397     int cap_left = v->cargo_cap - v->cargo.Count();
01398     if (!ge->cargo.Empty() && cap_left > 0) {
01399       uint cap = cap_left;
01400       uint count = ge->cargo.Count();
01401 
01402       /* Skip loading this vehicle if another train/vehicle is already handling
01403        * the same cargo type at this station */
01404       if (_settings_game.order.improved_load && cargo_left[v->cargo_type] <= 0) {
01405         SetBit(cargo_not_full, v->cargo_type);
01406         continue;
01407       }
01408 
01409       if (cap > count) cap = count;
01410       if (_settings_game.order.gradual_loading) {
01411         cap = min(cap, load_amount);
01412         cap_left = min(cap_left, load_amount);
01413       }
01414       if (_settings_game.order.improved_load) {
01415         /* Don't load stuff that is already 'reserved' for other vehicles */
01416         cap = min((uint)cargo_left[v->cargo_type], cap);
01417         count = cargo_left[v->cargo_type];
01418         cargo_left[v->cargo_type] -= cap;
01419       }
01420 
01421       /* Store whether the maximum possible load amount was loaded or not.*/
01422       if (count >= (uint)cap_left) {
01423         SetBit(full_load_amount, v->cargo_type);
01424       } else {
01425         ClrBit(full_load_amount, v->cargo_type);
01426       }
01427 
01428       if (v->cargo.Empty()) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
01429 
01430       /* TODO: Regarding this, when we do gradual loading, we
01431        * should first unload all vehicles and then start
01432        * loading them. Since this will cause
01433        * VEHICLE_TRIGGER_EMPTY to be called at the time when
01434        * the whole vehicle chain is really totally empty, the
01435        * completely_emptied assignment can then be safely
01436        * removed; that's how TTDPatch behaves too. --pasky */
01437       completely_emptied = false;
01438       anything_loaded = true;
01439 
01440       ge->cargo.MoveTo(&v->cargo, cap, StationCargoList::MTA_CARGO_LOAD, NULL, st->xy);
01441 
01442       st->time_since_load = 0;
01443       st->last_vehicle_type = v->type;
01444 
01445       if (ge->cargo.Empty()) {
01446         TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
01447         AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
01448       }
01449 
01450       unloading_time += cap;
01451 
01452       dirty_vehicle = dirty_station = true;
01453     }
01454 
01455     if (v->cargo.Count() >= v->cargo_cap) {
01456       SetBit(cargo_full, v->cargo_type);
01457     } else {
01458       SetBit(cargo_not_full, v->cargo_type);
01459     }
01460   }
01461 
01462   if (anything_loaded || anything_unloaded) {
01463     if (front->type == VEH_TRAIN) TriggerStationAnimation(st, st->xy, SAT_TRAIN_LOADS);
01464   }
01465 
01466   /* Only set completely_emptied, if we just unloaded all remaining cargo */
01467   completely_emptied &= anything_unloaded;
01468 
01469   /* We update these variables here, so gradual loading still fills
01470    * all wagons at the same time instead of using the same 'improved'
01471    * loading algorithm for the wagons (only fill wagon when there is
01472    * enough to fill the previous wagons) */
01473   if (_settings_game.order.improved_load && (front->current_order.GetLoadType() & OLFB_FULL_LOAD)) {
01474     /* Update left cargo */
01475     for (Vehicle *v = front; v != NULL; v = v->Next()) {
01476       int cap_left = v->cargo_cap - v->cargo.Count();
01477       if (cap_left > 0) cargo_left[v->cargo_type] -= cap_left;
01478     }
01479   }
01480 
01481   if (!anything_unloaded) delete payment;
01482 
01483   ClrBit(front->vehicle_flags, VF_STOP_LOADING);
01484   if (anything_loaded || anything_unloaded) {
01485     if (_settings_game.order.gradual_loading) {
01486       /* The time it takes to load one 'slice' of cargo or passengers depends
01487        * on the vehicle type - the values here are those found in TTDPatch */
01488       const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
01489 
01490       unloading_time = gradual_loading_wait_time[front->type];
01491     }
01492     /* We loaded less cargo than possible for all cargo types and it's not full
01493      * load and we're not supposed to wait any longer: stop loading. */
01494     if (!anything_unloaded && full_load_amount == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
01495         front->current_order_time >= (uint)max(front->current_order.wait_time - front->lateness_counter, 0)) {
01496       SetBit(front->vehicle_flags, VF_STOP_LOADING);
01497     }
01498   } else {
01499     bool finished_loading = true;
01500     if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
01501       if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
01502         /* if the aircraft carries passengers and is NOT full, then
01503          * continue loading, no matter how much mail is in */
01504         if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.Count()) ||
01505             (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
01506           finished_loading = false;
01507         }
01508       } else if (cargo_not_full != 0) {
01509         finished_loading = false;
01510       }
01511     }
01512     unloading_time = 20;
01513 
01514     SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
01515   }
01516 
01517   if (front->type == VEH_TRAIN) {
01518     /* Each platform tile is worth 2 rail vehicles. */
01519     int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
01520     if (overhang > 0) {
01521       unloading_time <<= 1;
01522       unloading_time += (overhang * unloading_time) / 8;
01523     }
01524   }
01525 
01526   /* Calculate the loading indicator fill percent and display
01527    * In the Game Menu do not display indicators
01528    * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
01529    * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
01530    * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
01531    */
01532   if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
01533     StringID percent_up_down = STR_NULL;
01534     int percent = CalcPercentVehicleFilled(front, &percent_up_down);
01535     if (front->fill_percent_te_id == INVALID_TE_ID) {
01536       front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
01537     } else {
01538       UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
01539     }
01540   }
01541 
01542   /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
01543   front->load_unload_ticks = max(1, unloading_time);
01544 
01545   if (completely_emptied) {
01546     TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
01547   }
01548 
01549   if (dirty_vehicle) {
01550     SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
01551     SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
01552     front->MarkDirty();
01553   }
01554   if (dirty_station) {
01555     st->MarkTilesDirty(true);
01556     SetWindowDirty(WC_STATION_VIEW, last_visited);
01557   }
01558 }
01559 
01565 void LoadUnloadStation(Station *st)
01566 {
01567   /* No vehicle is here... */
01568   if (st->loading_vehicles.empty()) return;
01569 
01570   Vehicle *last_loading = NULL;
01571   std::list<Vehicle *>::iterator iter;
01572 
01573   /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
01574   for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
01575     Vehicle *v = *iter;
01576 
01577     if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
01578 
01579     assert(v->load_unload_ticks != 0);
01580     if (--v->load_unload_ticks == 0) last_loading = v;
01581   }
01582 
01583   /* We only need to reserve and load/unload up to the last loading vehicle.
01584    * Anything else will be forgotten anyway after returning from this function.
01585    *
01586    * Especially this means we do _not_ need to reserve cargo for a single
01587    * consist in a station which is not allowed to load yet because its
01588    * load_unload_ticks is still not 0.
01589    */
01590   if (last_loading == NULL) return;
01591 
01592   int cargo_left[NUM_CARGO];
01593 
01594   for (uint i = 0; i < NUM_CARGO; i++) cargo_left[i] = st->goods[i].cargo.Count();
01595 
01596   for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
01597     Vehicle *v = *iter;
01598     if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v, cargo_left);
01599     if (v == last_loading) break;
01600   }
01601 
01602   /* Call the production machinery of industries */
01603   const Industry * const *isend = _cargo_delivery_destinations.End();
01604   for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
01605     TriggerIndustryProduction(*iid);
01606   }
01607   _cargo_delivery_destinations.Clear();
01608 }
01609 
01613 void CompaniesMonthlyLoop()
01614 {
01615   CompaniesGenStatistics();
01616   if (_settings_game.economy.inflation) {
01617     AddInflation();
01618     RecomputePrices();
01619   }
01620   CompaniesPayInterest();
01621   HandleEconomyFluctuations();
01622 }
01623 
01624 static void DoAcquireCompany(Company *c)
01625 {
01626   CompanyID ci = c->index;
01627 
01628   CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
01629   cni->FillData(c, Company::Get(_current_company));
01630 
01631   SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
01632   SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
01633   SetDParamStr(2, cni->company_name);
01634   SetDParamStr(3, cni->other_company_name);
01635   SetDParam(4, c->bankrupt_value);
01636   AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_MERGER, cni);
01637   AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
01638   Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
01639 
01640   ChangeOwnershipOfCompanyItems(ci, _current_company);
01641 
01642   if (c->bankrupt_value == 0) {
01643     Company *owner = Company::Get(_current_company);
01644     owner->current_loan += c->current_loan;
01645   }
01646 
01647   if (c->is_ai) AI::Stop(c->index);
01648 
01649   DeleteCompanyWindows(ci);
01650   InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
01651   InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
01652   InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
01653   InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
01654 
01655   delete c;
01656 }
01657 
01658 extern int GetAmountOwnedBy(const Company *c, Owner owner);
01659 
01669 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01670 {
01671   CommandCost cost(EXPENSES_OTHER);
01672   CompanyID target_company = (CompanyID)p1;
01673   Company *c = Company::GetIfValid(target_company);
01674 
01675   /* Check if buying shares is allowed (protection against modified clients)
01676    * Cannot buy own shares */
01677   if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
01678 
01679   /* Protect new companies from hostile takeovers */
01680   if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
01681 
01682   /* Those lines are here for network-protection (clients can be slow) */
01683   if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
01684 
01685   if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
01686     if (!c->is_ai) return cost; //  We can not buy out a real company (temporarily). TODO: well, enable it obviously.
01687 
01688     if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
01689   }
01690 
01691 
01692   cost.AddCost(CalculateCompanyValue(c) >> 2);
01693   if (flags & DC_EXEC) {
01694     OwnerByte *b = c->share_owners;
01695 
01696     while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
01697     *b = _current_company;
01698 
01699     for (int i = 0; c->share_owners[i] == _current_company;) {
01700       if (++i == 4) {
01701         c->bankrupt_value = 0;
01702         DoAcquireCompany(c);
01703         break;
01704       }
01705     }
01706     SetWindowDirty(WC_COMPANY, target_company);
01707     CompanyAdminUpdate(c);
01708   }
01709   return cost;
01710 }
01711 
01721 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01722 {
01723   CompanyID target_company = (CompanyID)p1;
01724   Company *c = Company::GetIfValid(target_company);
01725 
01726   /* Cannot sell own shares */
01727   if (c == NULL || _current_company == target_company) return CMD_ERROR;
01728 
01729   /* Check if selling shares is allowed (protection against modified clients).
01730    * However, we must sell shares of companies being closed down. */
01731   if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
01732 
01733   /* Those lines are here for network-protection (clients can be slow) */
01734   if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
01735 
01736   /* adjust it a little to make it less profitable to sell and buy */
01737   Money cost = CalculateCompanyValue(c) >> 2;
01738   cost = -(cost - (cost >> 7));
01739 
01740   if (flags & DC_EXEC) {
01741     OwnerByte *b = c->share_owners;
01742     while (*b != _current_company) b++; // share owners is guaranteed to contain company
01743     *b = COMPANY_SPECTATOR;
01744     SetWindowDirty(WC_COMPANY, target_company);
01745     CompanyAdminUpdate(c);
01746   }
01747   return CommandCost(EXPENSES_OTHER, cost);
01748 }
01749 
01762 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
01763 {
01764   CompanyID target_company = (CompanyID)p1;
01765   Company *c = Company::GetIfValid(target_company);
01766   if (c == NULL) return CMD_ERROR;
01767 
01768   /* Disable takeovers when not asked */
01769   if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
01770 
01771   /* Disable taking over the local company in single player */
01772   if (!_networking && _local_company == c->index) return CMD_ERROR;
01773 
01774   /* Do not allow companies to take over themselves */
01775   if (target_company == _current_company) return CMD_ERROR;
01776 
01777   /* Disable taking over when not allowed. */
01778   if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
01779 
01780   /* Get the cost here as the company is deleted in DoAcquireCompany. */
01781   CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
01782 
01783   if (flags & DC_EXEC) {
01784     DoAcquireCompany(c);
01785   }
01786   return cost;
01787 }