1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
8 /** @file economy.cpp Handling of the economy. */
9 
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "industry.h"
14 #include "town.h"
15 #include "news_func.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "ai/ai.hpp"
19 #include "aircraft.h"
20 #include "train.h"
21 #include "newgrf_engine.h"
22 #include "engine_base.h"
23 #include "ground_vehicle.hpp"
24 #include "newgrf_cargo.h"
25 #include "newgrf_sound.h"
26 #include "newgrf_industrytiles.h"
27 #include "newgrf_station.h"
28 #include "newgrf_airporttiles.h"
29 #include "object.h"
30 #include "strings_func.h"
31 #include "date_func.h"
32 #include "vehicle_func.h"
33 #include "sound_func.h"
34 #include "autoreplace_func.h"
35 #include "company_gui.h"
36 #include "signs_base.h"
37 #include "subsidy_base.h"
38 #include "subsidy_func.h"
39 #include "station_base.h"
40 #include "waypoint_base.h"
41 #include "economy_base.h"
42 #include "core/pool_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "cargo_type.h"
45 #include "water.h"
46 #include "game/game.hpp"
47 #include "cargomonitor.h"
48 #include "goal_base.h"
49 #include "story_base.h"
50 #include "linkgraph/refresh.h"
51 
52 #include "table/strings.h"
53 #include "table/pricebase.h"
54 
55 #include "safeguards.h"
56 
57 
58 /* Initialize the cargo payment-pool */
59 CargoPaymentPool _cargo_payment_pool("CargoPayment");
INSTANTIATE_POOL_METHODS(CargoPayment)60 INSTANTIATE_POOL_METHODS(CargoPayment)
61 
62 /**
63  * Multiply two integer values and shift the results to right.
64  *
65  * This function multiplies two integer values. The result is
66  * shifted by the amount of shift to right.
67  *
68  * @param a The first integer
69  * @param b The second integer
70  * @param shift The amount to shift the value to right.
71  * @return The shifted result
72  */
73 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
74 {
75 	return (int32)((int64)a * (int64)b >> shift);
76 }
77 
78 typedef std::vector<Industry *> SmallIndustryList;
79 
80 /**
81  * Score info, values used for computing the detailed performance rating.
82  */
83 const ScoreInfo _score_info[] = {
84 	{     120, 100}, // SCORE_VEHICLES
85 	{      80, 100}, // SCORE_STATIONS
86 	{   10000, 100}, // SCORE_MIN_PROFIT
87 	{   50000,  50}, // SCORE_MIN_INCOME
88 	{  100000, 100}, // SCORE_MAX_INCOME
89 	{   40000, 400}, // SCORE_DELIVERED
90 	{       8,  50}, // SCORE_CARGO
91 	{10000000,  50}, // SCORE_MONEY
92 	{  250000,  50}, // SCORE_LOAN
93 	{       0,   0}  // SCORE_TOTAL
94 };
95 
96 int64 _score_part[MAX_COMPANIES][SCORE_END];
97 Economy _economy;
98 Prices _price;
99 Money _additional_cash_required;
100 static PriceMultipliers _price_base_multiplier;
101 
102 /**
103  * Calculate the value of the company. That is the value of all
104  * assets (vehicles, stations, etc) and money minus the loan,
105  * except when including_loan is \c false which is useful when
106  * we want to calculate the value for bankruptcy.
107  * @param c              the company to get the value of.
108  * @param including_loan include the loan in the company value.
109  * @return the value of the company.
110  */
CalculateCompanyValue(const Company * c,bool including_loan)111 Money CalculateCompanyValue(const Company *c, bool including_loan)
112 {
113 	Owner owner = c->index;
114 
115 	uint num = 0;
116 
117 	for (const Station *st : Station::Iterate()) {
118 		if (st->owner == owner) num += CountBits((byte)st->facilities);
119 	}
120 
121 	Money value = num * _price[PR_STATION_VALUE] * 25;
122 
123 	for (const Vehicle *v : Vehicle::Iterate()) {
124 		if (v->owner != owner) continue;
125 
126 		if (v->type == VEH_TRAIN ||
127 				v->type == VEH_ROAD ||
128 				(v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
129 				v->type == VEH_SHIP) {
130 			value += v->value * 3 >> 1;
131 		}
132 	}
133 
134 	/* Add real money value */
135 	if (including_loan) value -= c->current_loan;
136 	value += c->money;
137 
138 	return std::max<Money>(value, 1);
139 }
140 
141 /**
142  * if update is set to true, the economy is updated with this score
143  *  (also the house is updated, should only be true in the on-tick event)
144  * @param update the economy with calculated score
145  * @param c company been evaluated
146  * @return actual score of this company
147  *
148  */
UpdateCompanyRatingAndValue(Company * c,bool update)149 int UpdateCompanyRatingAndValue(Company *c, bool update)
150 {
151 	Owner owner = c->index;
152 	int score = 0;
153 
154 	memset(_score_part[owner], 0, sizeof(_score_part[owner]));
155 
156 	/* Count vehicles */
157 	{
158 		Money min_profit = 0;
159 		bool min_profit_first = true;
160 		uint num = 0;
161 
162 		for (const Vehicle *v : Vehicle::Iterate()) {
163 			if (v->owner != owner) continue;
164 			if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
165 				if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
166 				if (v->age > 730) {
167 					/* Find the vehicle with the lowest amount of profit */
168 					if (min_profit_first || min_profit > v->profit_last_year) {
169 						min_profit = v->profit_last_year;
170 						min_profit_first = false;
171 					}
172 				}
173 			}
174 		}
175 
176 		min_profit >>= 8; // remove the fract part
177 
178 		_score_part[owner][SCORE_VEHICLES] = num;
179 		/* Don't allow negative min_profit to show */
180 		if (min_profit > 0) {
181 			_score_part[owner][SCORE_MIN_PROFIT] = min_profit;
182 		}
183 	}
184 
185 	/* Count stations */
186 	{
187 		uint num = 0;
188 		for (const Station *st : Station::Iterate()) {
189 			/* Only count stations that are actually serviced */
190 			if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
191 		}
192 		_score_part[owner][SCORE_STATIONS] = num;
193 	}
194 
195 	/* Generate statistics depending on recent income statistics */
196 	{
197 		int numec = std::min<uint>(c->num_valid_stat_ent, 12u);
198 		if (numec != 0) {
199 			const CompanyEconomyEntry *cee = c->old_economy;
200 			Money min_income = cee->income + cee->expenses;
201 			Money max_income = cee->income + cee->expenses;
202 
203 			do {
204 				min_income = std::min(min_income, cee->income + cee->expenses);
205 				max_income = std::max(max_income, cee->income + cee->expenses);
206 			} while (++cee, --numec);
207 
208 			if (min_income > 0) {
209 				_score_part[owner][SCORE_MIN_INCOME] = min_income;
210 			}
211 
212 			_score_part[owner][SCORE_MAX_INCOME] = max_income;
213 		}
214 	}
215 
216 	/* Generate score depending on amount of transported cargo */
217 	{
218 		int numec = std::min<uint>(c->num_valid_stat_ent, 4u);
219 		if (numec != 0) {
220 			const CompanyEconomyEntry *cee = c->old_economy;
221 			OverflowSafeInt64 total_delivered = 0;
222 			do {
223 				total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
224 			} while (++cee, --numec);
225 
226 			_score_part[owner][SCORE_DELIVERED] = total_delivered;
227 		}
228 	}
229 
230 	/* Generate score for variety of cargo */
231 	{
232 		_score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
233 	}
234 
235 	/* Generate score for company's money */
236 	{
237 		if (c->money > 0) {
238 			_score_part[owner][SCORE_MONEY] = c->money;
239 		}
240 	}
241 
242 	/* Generate score for loan */
243 	{
244 		_score_part[owner][SCORE_LOAN] = _score_info[SCORE_LOAN].needed - c->current_loan;
245 	}
246 
247 	/* Now we calculate the score for each item.. */
248 	{
249 		int total_score = 0;
250 		int s;
251 		score = 0;
252 		for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
253 			/* Skip the total */
254 			if (i == SCORE_TOTAL) continue;
255 			/*  Check the score */
256 			s = Clamp<int64>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
257 			score += s;
258 			total_score += _score_info[i].score;
259 		}
260 
261 		_score_part[owner][SCORE_TOTAL] = score;
262 
263 		/*  We always want the score scaled to SCORE_MAX (1000) */
264 		if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
265 	}
266 
267 	if (update) {
268 		c->old_economy[0].performance_history = score;
269 		UpdateCompanyHQ(c->location_of_HQ, score);
270 		c->old_economy[0].company_value = CalculateCompanyValue(c);
271 	}
272 
273 	SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
274 	return score;
275 }
276 
277 /**
278  * Change the ownership of all the items of a company.
279  * @param old_owner The company that gets removed.
280  * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
281  */
ChangeOwnershipOfCompanyItems(Owner old_owner,Owner new_owner)282 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
283 {
284 	/* We need to set _current_company to old_owner before we try to move
285 	 * the client. This is needed as it needs to know whether "you" really
286 	 * are the current local company. */
287 	Backup<CompanyID> cur_company(_current_company, old_owner, FILE_LINE);
288 	/* In all cases, make spectators of clients connected to that company */
289 	if (_networking) NetworkClientsToSpectators(old_owner);
290 	if (old_owner == _local_company) {
291 		/* Single player cheated to AI company.
292 		 * There are no spectators in singleplayer mode, so we must pick some other company. */
293 		assert(!_networking);
294 		Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
295 		for (const Company *c : Company::Iterate()) {
296 			if (c->index != old_owner) {
297 				SetLocalCompany(c->index);
298 				break;
299 			}
300 		}
301 		cur_company2.Restore();
302 		assert(old_owner != _local_company);
303 	}
304 
305 	assert(old_owner != new_owner);
306 
307 	{
308 		uint i;
309 
310 		/* See if the old_owner had shares in other companies */
311 		for (const Company *c : Company::Iterate()) {
312 			for (i = 0; i < 4; i++) {
313 				if (c->share_owners[i] == old_owner) {
314 					/* Sell its shares */
315 					CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
316 					/* Because we are in a DoCommand, we can't just execute another one and
317 					 *  expect the money to be removed. We need to do it ourself! */
318 					SubtractMoneyFromCompany(res);
319 				}
320 			}
321 		}
322 
323 		/* Sell all the shares that people have on this company */
324 		Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
325 		const Company *c = Company::Get(old_owner);
326 		for (i = 0; i < 4; i++) {
327 			if (c->share_owners[i] == INVALID_OWNER) continue;
328 
329 			if (c->bankrupt_value == 0 && c->share_owners[i] == new_owner) {
330 				/* You are the one buying the company; so don't sell the shares back to you. */
331 				Company::Get(new_owner)->share_owners[i] = INVALID_OWNER;
332 			} else {
333 				cur_company2.Change(c->share_owners[i]);
334 				/* Sell the shares */
335 				CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
336 				/* Because we are in a DoCommand, we can't just execute another one and
337 				 *  expect the money to be removed. We need to do it ourself! */
338 				SubtractMoneyFromCompany(res);
339 			}
340 		}
341 		cur_company2.Restore();
342 	}
343 
344 	/* Temporarily increase the company's money, to be sure that
345 	 * removing their property doesn't fail because of lack of money.
346 	 * Not too drastically though, because it could overflow */
347 	if (new_owner == INVALID_OWNER) {
348 		Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
349 	}
350 
351 	for (Subsidy *s : Subsidy::Iterate()) {
352 		if (s->awarded == old_owner) {
353 			if (new_owner == INVALID_OWNER) {
354 				delete s;
355 			} else {
356 				s->awarded = new_owner;
357 			}
358 		}
359 	}
360 	if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
361 
362 	/* Take care of rating and transport rights in towns */
363 	for (Town *t : Town::Iterate()) {
364 		/* If a company takes over, give the ratings to that company. */
365 		if (new_owner != INVALID_OWNER) {
366 			if (HasBit(t->have_ratings, old_owner)) {
367 				if (HasBit(t->have_ratings, new_owner)) {
368 					/* use max of the two ratings. */
369 					t->ratings[new_owner] = std::max(t->ratings[new_owner], t->ratings[old_owner]);
370 				} else {
371 					SetBit(t->have_ratings, new_owner);
372 					t->ratings[new_owner] = t->ratings[old_owner];
373 				}
374 			}
375 		}
376 
377 		/* Reset the ratings for the old owner */
378 		t->ratings[old_owner] = RATING_INITIAL;
379 		ClrBit(t->have_ratings, old_owner);
380 
381 		/* Transfer exclusive rights */
382 		if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
383 			if (new_owner != INVALID_OWNER) {
384 				t->exclusivity = new_owner;
385 			} else {
386 				t->exclusive_counter = 0;
387 				t->exclusivity = INVALID_COMPANY;
388 			}
389 		}
390 	}
391 
392 	{
393 		for (Vehicle *v : Vehicle::Iterate()) {
394 			if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
395 				if (new_owner == INVALID_OWNER) {
396 					if (v->Previous() == nullptr) delete v;
397 				} else {
398 					if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
399 					if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
400 				}
401 			}
402 		}
403 	}
404 
405 	/* In all cases clear replace engine rules.
406 	 * Even if it was copied, it could interfere with new owner's rules */
407 	RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
408 
409 	if (new_owner == INVALID_OWNER) {
410 		RemoveAllGroupsForCompany(old_owner);
411 	} else {
412 		for (Group *g : Group::Iterate()) {
413 			if (g->owner == old_owner) g->owner = new_owner;
414 		}
415 	}
416 
417 	{
418 		FreeUnitIDGenerator unitidgen[] = {
419 			FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD,     new_owner),
420 			FreeUnitIDGenerator(VEH_SHIP,  new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
421 		};
422 
423 		/* Override company settings to new company defaults in case we need to convert them.
424 		 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
425 		 */
426 		if (new_owner != INVALID_OWNER) {
427 			Company *old_company = Company::Get(old_owner);
428 			Company *new_company = Company::Get(new_owner);
429 
430 			old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
431 			old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
432 			old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
433 			old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
434 			old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
435 		}
436 
437 		for (Vehicle *v : Vehicle::Iterate()) {
438 			if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
439 				assert(new_owner != INVALID_OWNER);
440 
441 				/* Correct default values of interval settings while maintaining custom set ones.
442 				 * This prevents invalid values on mismatching company defaults being accepted.
443 				 */
444 				if (!v->ServiceIntervalIsCustom()) {
445 					Company *new_company = Company::Get(new_owner);
446 
447 					/* Technically, passing the interval is not needed as the command will query the default value itself.
448 					 * However, do not rely on that behaviour.
449 					 */
450 					int interval = CompanyServiceInterval(new_company, v->type);
451 					DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
452 				}
453 
454 				v->owner = new_owner;
455 
456 				/* Owner changes, clear cache */
457 				v->colourmap = PAL_NONE;
458 				v->InvalidateNewGRFCache();
459 
460 				if (v->IsEngineCountable()) {
461 					GroupStatistics::CountEngine(v, 1);
462 				}
463 				if (v->IsPrimaryVehicle()) {
464 					GroupStatistics::CountVehicle(v, 1);
465 					v->unitnumber = unitidgen[v->type].NextID();
466 				}
467 
468 				/* Invalidate the vehicle's cargo payment "owner cache". */
469 				if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
470 			}
471 		}
472 
473 		if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
474 	}
475 
476 	/*  Change ownership of tiles */
477 	{
478 		TileIndex tile = 0;
479 		do {
480 			ChangeTileOwner(tile, old_owner, new_owner);
481 		} while (++tile != MapSize());
482 
483 		if (new_owner != INVALID_OWNER) {
484 			/* Update all signals because there can be new segment that was owned by two companies
485 			 * and signals were not propagated
486 			 * Similar with crossings - it is needed to bar crossings that weren't before
487 			 * because of different owner of crossing and approaching train */
488 			tile = 0;
489 
490 			do {
491 				if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
492 					TrackBits tracks = GetTrackBits(tile);
493 					do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
494 						Track track = RemoveFirstTrack(&tracks);
495 						if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
496 					} while (tracks != TRACK_BIT_NONE);
497 				} else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
498 					UpdateLevelCrossing(tile);
499 				}
500 			} while (++tile != MapSize());
501 		}
502 
503 		/* update signals in buffer */
504 		UpdateSignalsInBuffer();
505 	}
506 
507 	/* Add airport infrastructure count of the old company to the new one. */
508 	if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
509 
510 	/* convert owner of stations (including deleted ones, but excluding buoys) */
511 	for (Station *st : Station::Iterate()) {
512 		if (st->owner == old_owner) {
513 			/* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
514 			 * also, drawing station window would cause reading invalid company's colour */
515 			st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
516 		}
517 	}
518 
519 	/* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
520 	for (Waypoint *wp : Waypoint::Iterate()) {
521 		if (wp->owner == old_owner) {
522 			wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
523 		}
524 	}
525 
526 	for (Sign *si : Sign::Iterate()) {
527 		if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
528 	}
529 
530 	/* Remove Game Script created Goals, CargoMonitors and Story pages. */
531 	for (Goal *g : Goal::Iterate()) {
532 		if (g->company == old_owner) delete g;
533 	}
534 
535 	ClearCargoPickupMonitoring(old_owner);
536 	ClearCargoDeliveryMonitoring(old_owner);
537 
538 	for (StoryPage *sp : StoryPage::Iterate()) {
539 		if (sp->company == old_owner) delete sp;
540 	}
541 
542 	/* Change colour of existing windows */
543 	if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
544 
545 	cur_company.Restore();
546 
547 	MarkWholeScreenDirty();
548 }
549 
550 /**
551  * Check for bankruptcy of a company. Called every three months.
552  * @param c Company to check.
553  */
CompanyCheckBankrupt(Company * c)554 static void CompanyCheckBankrupt(Company *c)
555 {
556 	/*  If the company has money again, it does not go bankrupt */
557 	if (c->money - c->current_loan >= -_economy.max_loan) {
558 		int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
559 		c->months_of_bankruptcy = 0;
560 		c->bankrupt_asked = 0;
561 		if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
562 		return;
563 	}
564 
565 	c->months_of_bankruptcy++;
566 
567 	switch (c->months_of_bankruptcy) {
568 		/* All the boring cases (months) with a bad balance where no action is taken */
569 		case 0:
570 		case 1:
571 		case 2:
572 		case 3:
573 
574 		case 5:
575 		case 6:
576 
577 		case 8:
578 		case 9:
579 			break;
580 
581 		/* Warn about bankruptcy after 3 months */
582 		case 4: {
583 			CompanyNewsInformation *cni = new CompanyNewsInformation(c);
584 			SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
585 			SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
586 			SetDParamStr(2, cni->company_name);
587 			AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
588 			AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
589 			Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
590 			break;
591 		}
592 
593 		/* Offer company for sale after 6 months */
594 		case 7: {
595 			/* Don't consider the loan */
596 			Money val = CalculateCompanyValue(c, false);
597 
598 			c->bankrupt_value = val;
599 			c->bankrupt_asked = 1 << c->index; // Don't ask the owner
600 			c->bankrupt_timeout = 0;
601 
602 			/* The company assets should always have some value */
603 			assert(c->bankrupt_value > 0);
604 			break;
605 		}
606 
607 		/* Bankrupt company after 6 months (if the company has no value) or latest
608 		 * after 9 months (if it still had value after 6 months) */
609 		default:
610 		case 10: {
611 			if (!_networking && _local_company == c->index) {
612 				/* If we are in singleplayer mode, leave the company playing. Eg. there
613 				 * is no THE-END, otherwise mark the client as spectator to make sure
614 				 * they are no longer in control of this company. However... when you
615 				 * join another company (cheat) the "unowned" company can bankrupt. */
616 				c->bankrupt_asked = MAX_UVALUE(CompanyMask);
617 				break;
618 			}
619 
620 			/* Actually remove the company, but not when we're a network client.
621 			 * In case of network clients we will be getting a command from the
622 			 * server. It is done in this way as we are called from the
623 			 * StateGameLoop which can't change the current company, and thus
624 			 * updating the local company triggers an assert later on. In the
625 			 * case of a network game the command will be processed at a time
626 			 * that changing the current company is okay. In case of single
627 			 * player we are sure (the above check) that we are not the local
628 			 * company and thus we won't be moved. */
629 			if (!_networking || _network_server) {
630 				DoCommandP(0, CCA_DELETE | (c->index << 16) | (CRR_BANKRUPT << 24), 0, CMD_COMPANY_CTRL);
631 				return;
632 			}
633 			break;
634 		}
635 	}
636 
637 	if (CeilDiv(c->months_of_bankruptcy, 3) != CeilDiv(c->months_of_bankruptcy - 1, 3)) CompanyAdminUpdate(c);
638 }
639 
640 /**
641  * Update the finances of all companies.
642  * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
643  */
CompaniesGenStatistics()644 static void CompaniesGenStatistics()
645 {
646 	/* Check for bankruptcy each month */
647 	for (Company *c : Company::Iterate()) {
648 		CompanyCheckBankrupt(c);
649 	}
650 
651 	Backup<CompanyID> cur_company(_current_company, FILE_LINE);
652 
653 	if (!_settings_game.economy.infrastructure_maintenance) {
654 		for (const Station *st : Station::Iterate()) {
655 			cur_company.Change(st->owner);
656 			CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
657 			SubtractMoneyFromCompany(cost);
658 		}
659 	} else {
660 		/* Improved monthly infrastructure costs. */
661 		for (const Company *c : Company::Iterate()) {
662 			cur_company.Change(c->index);
663 
664 			CommandCost cost(EXPENSES_PROPERTY);
665 			uint32 rail_total = c->infrastructure.GetRailTotal();
666 			for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
667 				if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
668 			}
669 			cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
670 			uint32 road_total = c->infrastructure.GetRoadTotal();
671 			uint32 tram_total = c->infrastructure.GetTramTotal();
672 			for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
673 				if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
674 			}
675 			cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
676 			cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
677 			cost.AddCost(AirportMaintenanceCost(c->index));
678 
679 			SubtractMoneyFromCompany(cost);
680 		}
681 	}
682 	cur_company.Restore();
683 
684 	/* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
685 	if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
686 
687 	for (Company *c : Company::Iterate()) {
688 		/* Drop the oldest history off the end */
689 		std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS);
690 		c->old_economy[0] = c->cur_economy;
691 		c->cur_economy = {};
692 
693 		if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
694 
695 		UpdateCompanyRatingAndValue(c, true);
696 		if (c->block_preview != 0) c->block_preview--;
697 	}
698 
699 	SetWindowDirty(WC_INCOME_GRAPH, 0);
700 	SetWindowDirty(WC_OPERATING_PROFIT, 0);
701 	SetWindowDirty(WC_DELIVERED_CARGO, 0);
702 	SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
703 	SetWindowDirty(WC_COMPANY_VALUE, 0);
704 	SetWindowDirty(WC_COMPANY_LEAGUE, 0);
705 }
706 
707 /**
708  * Add monthly inflation
709  * @param check_year Shall the inflation get stopped after 170 years?
710  * @return true if inflation is maxed and nothing was changed
711  */
AddInflation(bool check_year)712 bool AddInflation(bool check_year)
713 {
714 	/* The cargo payment inflation differs from the normal inflation, so the
715 	 * relative amount of money you make with a transport decreases slowly over
716 	 * the 170 years. After a few hundred years we reach a level in which the
717 	 * games will become unplayable as the maximum income will be less than
718 	 * the minimum running cost.
719 	 *
720 	 * Furthermore there are a lot of inflation related overflows all over the
721 	 * place. Solving them is hardly possible because inflation will always
722 	 * reach the overflow threshold some day. So we'll just perform the
723 	 * inflation mechanism during the first 170 years (the amount of years that
724 	 * one had in the original TTD) and stop doing the inflation after that
725 	 * because it only causes problems that can't be solved nicely and the
726 	 * inflation doesn't add anything after that either; it even makes playing
727 	 * it impossible due to the diverging cost and income rates.
728 	 */
729 	if (check_year && (_cur_year < ORIGINAL_BASE_YEAR || _cur_year >= ORIGINAL_MAX_YEAR)) return true;
730 
731 	if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
732 
733 	/* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
734 	 * scaled by 65536
735 	 * 12 -> months per year
736 	 * This is only a good approximation for small values
737 	 */
738 	_economy.inflation_prices  += (_economy.inflation_prices  * _economy.infl_amount    * 54) >> 16;
739 	_economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
740 
741 	if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
742 	if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
743 
744 	return false;
745 }
746 
747 /**
748  * Computes all prices, payments and maximum loan.
749  */
RecomputePrices()750 void RecomputePrices()
751 {
752 	/* Setup maximum loan */
753 	_economy.max_loan = ((uint64)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
754 
755 	/* Setup price bases */
756 	for (Price i = PR_BEGIN; i < PR_END; i++) {
757 		Money price = _price_base_specs[i].start_price;
758 
759 		/* Apply difficulty settings */
760 		uint mod = 1;
761 		switch (_price_base_specs[i].category) {
762 			case PCAT_RUNNING:
763 				mod = _settings_game.difficulty.vehicle_costs;
764 				break;
765 
766 			case PCAT_CONSTRUCTION:
767 				mod = _settings_game.difficulty.construction_cost;
768 				break;
769 
770 			default: break;
771 		}
772 		switch (mod) {
773 			case 0: price *= 6; break;
774 			case 1: price *= 8; break; // normalised to 1 below
775 			case 2: price *= 9; break;
776 			default: NOT_REACHED();
777 		}
778 
779 		/* Apply inflation */
780 		price = (int64)price * _economy.inflation_prices;
781 
782 		/* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
783 		int shift = _price_base_multiplier[i] - 16 - 3;
784 		if (shift >= 0) {
785 			price <<= shift;
786 		} else {
787 			price >>= -shift;
788 		}
789 
790 		/* Make sure the price does not get reduced to zero.
791 		 * Zero breaks quite a few commands that use a zero
792 		 * cost to see whether something got changed or not
793 		 * and based on that cause an error. When the price
794 		 * is zero that fails even when things are done. */
795 		if (price == 0) {
796 			price = Clamp(_price_base_specs[i].start_price, -1, 1);
797 			/* No base price should be zero, but be sure. */
798 			assert(price != 0);
799 		}
800 		/* Store value */
801 		_price[i] = price;
802 	}
803 
804 	/* Setup cargo payment */
805 	for (CargoSpec *cs : CargoSpec::Iterate()) {
806 		cs->current_payment = (cs->initial_payment * (int64)_economy.inflation_payment) >> 16;
807 	}
808 
809 	SetWindowClassesDirty(WC_BUILD_VEHICLE);
810 	SetWindowClassesDirty(WC_REPLACE_VEHICLE);
811 	SetWindowClassesDirty(WC_VEHICLE_DETAILS);
812 	SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
813 	InvalidateWindowData(WC_PAYMENT_RATES, 0);
814 }
815 
816 /** Let all companies pay the monthly interest on their loan. */
CompaniesPayInterest()817 static void CompaniesPayInterest()
818 {
819 	Backup<CompanyID> cur_company(_current_company, FILE_LINE);
820 	for (const Company *c : Company::Iterate()) {
821 		cur_company.Change(c->index);
822 
823 		/* Over a year the paid interest should be "loan * interest percentage",
824 		 * but... as that number is likely not dividable by 12 (pay each month),
825 		 * one needs to account for that in the monthly fee calculations.
826 		 * To easily calculate what one should pay "this" month, you calculate
827 		 * what (total) should have been paid up to this month and you subtract
828 		 * whatever has been paid in the previous months. This will mean one month
829 		 * it'll be a bit more and the other it'll be a bit less than the average
830 		 * monthly fee, but on average it will be exact.
831 		 * In order to prevent cheating or abuse (just not paying interest by not
832 		 * taking a loan we make companies pay interest on negative cash as well
833 		 */
834 		Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
835 		if (c->money < 0) {
836 			yearly_fee += -c->money *_economy.interest_rate / 100;
837 		}
838 		Money up_to_previous_month = yearly_fee * _cur_month / 12;
839 		Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
840 
841 		SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
842 
843 		SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
844 	}
845 	cur_company.Restore();
846 }
847 
HandleEconomyFluctuations()848 static void HandleEconomyFluctuations()
849 {
850 	if (_settings_game.difficulty.economy != 0) {
851 		/* When economy is Fluctuating, decrease counter */
852 		_economy.fluct--;
853 	} else if (EconomyIsInRecession()) {
854 		/* When it's Steady and we are in recession, end it now */
855 		_economy.fluct = -12;
856 	} else {
857 		/* No need to do anything else in other cases */
858 		return;
859 	}
860 
861 	if (_economy.fluct == 0) {
862 		_economy.fluct = -(int)GB(Random(), 0, 2);
863 		AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
864 	} else if (_economy.fluct == -12) {
865 		_economy.fluct = GB(Random(), 0, 8) + 312;
866 		AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
867 	}
868 }
869 
870 
871 /**
872  * Reset changes to the price base multipliers.
873  */
ResetPriceBaseMultipliers()874 void ResetPriceBaseMultipliers()
875 {
876 	memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
877 }
878 
879 /**
880  * Change a price base by the given factor.
881  * The price base is altered by factors of two.
882  * NewBaseCost = OldBaseCost * 2^n
883  * @param price Index of price base to change.
884  * @param factor Amount to change by.
885  */
SetPriceBaseMultiplier(Price price,int factor)886 void SetPriceBaseMultiplier(Price price, int factor)
887 {
888 	assert(price < PR_END);
889 	_price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
890 }
891 
892 /**
893  * Initialize the variables that will maintain the daily industry change system.
894  * @param init_counter specifies if the counter is required to be initialized
895  */
StartupIndustryDailyChanges(bool init_counter)896 void StartupIndustryDailyChanges(bool init_counter)
897 {
898 	uint map_size = MapLogX() + MapLogY();
899 	/* After getting map size, it needs to be scaled appropriately and divided by 31,
900 	 * which stands for the days in a month.
901 	 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
902 	 * would not be needed.
903 	 * Since it is based on "fractional parts", the leftover days will not make much of a difference
904 	 * on the overall total number of changes performed */
905 	_economy.industry_daily_increment = (1 << map_size) / 31;
906 
907 	if (init_counter) {
908 		/* A new game or a savegame from an older version will require the counter to be initialized */
909 		_economy.industry_daily_change_counter = 0;
910 	}
911 }
912 
StartupEconomy()913 void StartupEconomy()
914 {
915 	_economy.interest_rate = _settings_game.difficulty.initial_interest;
916 	_economy.infl_amount = _settings_game.difficulty.initial_interest;
917 	_economy.infl_amount_pr = std::max(0, _settings_game.difficulty.initial_interest - 1);
918 	_economy.fluct = GB(Random(), 0, 8) + 168;
919 
920 	if (_settings_game.economy.inflation) {
921 		/* Apply inflation that happened before our game start year. */
922 		int months = (std::min(_cur_year, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR) * 12;
923 		for (int i = 0; i < months; i++) {
924 			AddInflation(false);
925 		}
926 	}
927 
928 	/* Set up prices */
929 	RecomputePrices();
930 
931 	StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
932 
933 }
934 
935 /**
936  * Resets economy to initial values
937  */
InitializeEconomy()938 void InitializeEconomy()
939 {
940 	_economy.inflation_prices = _economy.inflation_payment = 1 << 16;
941 	ClearCargoPickupMonitoring();
942 	ClearCargoDeliveryMonitoring();
943 }
944 
945 /**
946  * Determine a certain price
947  * @param index Price base
948  * @param cost_factor Price factor
949  * @param grf_file NewGRF to use local price multipliers from.
950  * @param shift Extra bit shifting after the computation
951  * @return Price
952  */
GetPrice(Price index,uint cost_factor,const GRFFile * grf_file,int shift)953 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
954 {
955 	if (index >= PR_END) return 0;
956 
957 	Money cost = _price[index] * cost_factor;
958 	if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
959 
960 	if (shift >= 0) {
961 		cost <<= shift;
962 	} else {
963 		cost >>= -shift;
964 	}
965 
966 	return cost;
967 }
968 
GetTransportedGoodsIncome(uint num_pieces,uint dist,byte transit_days,CargoID cargo_type)969 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
970 {
971 	const CargoSpec *cs = CargoSpec::Get(cargo_type);
972 	if (!cs->IsValid()) {
973 		/* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
974 		return 0;
975 	}
976 
977 	/* Use callback to calculate cargo profit, if available */
978 	if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
979 		uint32 var18 = std::min(dist, 0xFFFFu) | (std::min(num_pieces, 0xFFu) << 16) | (transit_days << 24);
980 		uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
981 		if (callback != CALLBACK_FAILED) {
982 			int result = GB(callback, 0, 14);
983 
984 			/* Simulate a 15 bit signed value */
985 			if (HasBit(callback, 14)) result -= 0x4000;
986 
987 			/* "The result should be a signed multiplier that gets multiplied
988 			 * by the amount of cargo moved and the price factor, then gets
989 			 * divided by 8192." */
990 			return result * num_pieces * cs->current_payment / 8192;
991 		}
992 	}
993 
994 	static const int MIN_TIME_FACTOR = 31;
995 	static const int MAX_TIME_FACTOR = 255;
996 
997 	const int days1 = cs->transit_days[0];
998 	const int days2 = cs->transit_days[1];
999 	const int days_over_days1 = std::max(   transit_days - days1, 0);
1000 	const int days_over_days2 = std::max(days_over_days1 - days2, 0);
1001 
1002 	/*
1003 	 * The time factor is calculated based on the time it took
1004 	 * (transit_days) compared two cargo-depending values. The
1005 	 * range is divided into three parts:
1006 	 *
1007 	 *  - constant for fast transits
1008 	 *  - linear decreasing with time with a slope of -1 for medium transports
1009 	 *  - linear decreasing with time with a slope of -2 for slow transports
1010 	 *
1011 	 */
1012 	const int time_factor = std::max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1013 
1014 	return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1015 }
1016 
1017 /** The industries we've currently brought cargo to. */
1018 static SmallIndustryList _cargo_delivery_destinations;
1019 
1020 /**
1021  * Transfer goods from station to industry.
1022  * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1023  * @param st The station that accepted the cargo
1024  * @param cargo_type Type of cargo delivered
1025  * @param num_pieces Amount of cargo delivered
1026  * @param source The source of the cargo
1027  * @param company The company delivering the cargo
1028  * @return actually accepted pieces of cargo
1029  */
DeliverGoodsToIndustry(const Station * st,CargoID cargo_type,uint num_pieces,IndustryID source,CompanyID company)1030 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1031 {
1032 	/* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1033 	 * This fails in three cases:
1034 	 *  1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1035 	 *  2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1036 	 *  3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1037 	 */
1038 
1039 	uint accepted = 0;
1040 
1041 	for (Industry *ind : st->industries_near) {
1042 		if (num_pieces == 0) break;
1043 
1044 		if (ind->index == source) continue;
1045 
1046 		uint cargo_index;
1047 		for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1048 			if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1049 		}
1050 		/* Check if matching cargo has been found */
1051 		if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1052 
1053 		/* Check if industry temporarily refuses acceptance */
1054 		if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1055 
1056 		if (ind->exclusive_supplier != INVALID_OWNER && ind->exclusive_supplier != st->owner) continue;
1057 
1058 		/* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1059 		include(_cargo_delivery_destinations, ind);
1060 
1061 		uint amount = std::min(num_pieces, 0xFFFFu - ind->incoming_cargo_waiting[cargo_index]);
1062 		ind->incoming_cargo_waiting[cargo_index] += amount;
1063 		ind->last_cargo_accepted_at[cargo_index] = _date;
1064 		num_pieces -= amount;
1065 		accepted += amount;
1066 
1067 		/* Update the cargo monitor. */
1068 		AddCargoDelivery(cargo_type, company, amount, ST_INDUSTRY, source, st, ind->index);
1069 	}
1070 
1071 	return accepted;
1072 }
1073 
1074 /**
1075  * Delivers goods to industries/towns and calculates the payment
1076  * @param num_pieces amount of cargo delivered
1077  * @param cargo_type the type of cargo that is delivered
1078  * @param dest Station the cargo has been unloaded
1079  * @param source_tile The origin of the cargo for distance calculation
1080  * @param days_in_transit Travel time
1081  * @param company The company delivering the cargo
1082  * @param src_type Type of source of cargo (industry, town, headquarters)
1083  * @param src Index of source of cargo
1084  * @return Revenue for delivering cargo
1085  * @note The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery
1086  */
DeliverGoods(int num_pieces,CargoID cargo_type,StationID dest,TileIndex source_tile,byte days_in_transit,Company * company,SourceType src_type,SourceID src)1087 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)
1088 {
1089 	assert(num_pieces > 0);
1090 
1091 	Station *st = Station::Get(dest);
1092 
1093 	/* Give the goods to the industry. */
1094 	uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY, company->index);
1095 
1096 	/* If this cargo type is always accepted, accept all */
1097 	uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
1098 
1099 	/* Update station statistics */
1100 	if (accepted_total > 0) {
1101 		SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1102 		SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1103 		SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1104 	}
1105 
1106 	/* Update company statistics */
1107 	company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1108 
1109 	/* Increase town's counter for town effects */
1110 	const CargoSpec *cs = CargoSpec::Get(cargo_type);
1111 	st->town->received[cs->town_effect].new_act += accepted_total;
1112 
1113 	/* Determine profit */
1114 	Money profit = GetTransportedGoodsIncome(accepted_total, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1115 
1116 	/* Update the cargo monitor. */
1117 	AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src_type, src, st);
1118 
1119 	/* Modify profit if a subsidy is in effect */
1120 	if (CheckSubsidised(cargo_type, company->index, src_type, src, st))  {
1121 		switch (_settings_game.difficulty.subsidy_multiplier) {
1122 			case 0:  profit += profit >> 1; break;
1123 			case 1:  profit *= 2; break;
1124 			case 2:  profit *= 3; break;
1125 			default: profit *= 4; break;
1126 		}
1127 	}
1128 
1129 	return profit;
1130 }
1131 
1132 /**
1133  * Inform the industry about just delivered cargo
1134  * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1135  * @param i The industry to process
1136  */
TriggerIndustryProduction(Industry * i)1137 static void TriggerIndustryProduction(Industry *i)
1138 {
1139 	const IndustrySpec *indspec = GetIndustrySpec(i->type);
1140 	uint16 callback = indspec->callback_mask;
1141 
1142 	i->was_cargo_delivered = true;
1143 
1144 	if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1145 		if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1146 			IndustryProductionCallback(i, 0);
1147 		} else {
1148 			SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1149 		}
1150 	} else {
1151 		for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) {
1152 			uint cargo_waiting = i->incoming_cargo_waiting[ci_in];
1153 			if (cargo_waiting == 0) continue;
1154 
1155 			for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) {
1156 				i->produced_cargo_waiting[ci_out] = std::min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFFu);
1157 			}
1158 
1159 			i->incoming_cargo_waiting[ci_in] = 0;
1160 		}
1161 	}
1162 
1163 	TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1164 	StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1165 }
1166 
1167 /**
1168  * Makes us a new cargo payment helper.
1169  * @param front The front of the train
1170  */
CargoPayment(Vehicle * front)1171 CargoPayment::CargoPayment(Vehicle *front) :
1172 	front(front),
1173 	current_station(front->last_station_visited)
1174 {
1175 }
1176 
~CargoPayment()1177 CargoPayment::~CargoPayment()
1178 {
1179 	if (this->CleaningPool()) return;
1180 
1181 	this->front->cargo_payment = nullptr;
1182 
1183 	if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1184 
1185 	Backup<CompanyID> cur_company(_current_company, this->front->owner, FILE_LINE);
1186 
1187 	SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1188 	this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1189 
1190 	if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1191 		SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1192 	}
1193 
1194 	if (this->visual_transfer != 0) {
1195 		ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1196 				this->front->z_pos, this->visual_transfer, -this->visual_profit);
1197 	} else if (this->visual_profit != 0) {
1198 		ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1199 				this->front->z_pos, -this->visual_profit);
1200 	}
1201 
1202 	cur_company.Restore();
1203 }
1204 
1205 /**
1206  * Handle payment for final delivery of the given cargo packet.
1207  * @param cp The cargo packet to pay for.
1208  * @param count The number of packets to pay for.
1209  */
PayFinalDelivery(const CargoPacket * cp,uint count)1210 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1211 {
1212 	if (this->owner == nullptr) {
1213 		this->owner = Company::Get(this->front->owner);
1214 	}
1215 
1216 	/* Handle end of route payment */
1217 	Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1218 	this->route_profit += profit;
1219 
1220 	/* The vehicle's profit is whatever route profit there is minus feeder shares. */
1221 	this->visual_profit += profit - cp->FeederShare(count);
1222 }
1223 
1224 /**
1225  * Handle payment for transfer of the given cargo packet.
1226  * @param cp The cargo packet to pay for; actual payment won't be made!.
1227  * @param count The number of packets to pay for.
1228  * @return The amount of money paid for the transfer.
1229  */
PayTransfer(const CargoPacket * cp,uint count)1230 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
1231 {
1232 	Money profit = -cp->FeederShare(count) + GetTransportedGoodsIncome(
1233 			count,
1234 			/* pay transfer vehicle the difference between the payment for the journey from
1235 			 * the source to the current point, and the sum of the previous transfer payments */
1236 			DistanceManhattan(cp->SourceStationXY(), Station::Get(this->current_station)->xy),
1237 			cp->DaysInTransit(),
1238 			this->ct);
1239 
1240 	profit = profit * _settings_game.economy.feeder_payment_share / 100;
1241 
1242 	this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1243 	return profit; // account for the (virtual) profit already made for the cargo packet
1244 }
1245 
1246 /**
1247  * Prepare the vehicle to be unloaded.
1248  * @param front_v the vehicle to be unloaded
1249  */
PrepareUnload(Vehicle * front_v)1250 void PrepareUnload(Vehicle *front_v)
1251 {
1252 	Station *curr_station = Station::Get(front_v->last_station_visited);
1253 	curr_station->loading_vehicles.push_back(front_v);
1254 
1255 	/* At this moment loading cannot be finished */
1256 	ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1257 
1258 	/* Start unloading at the first possible moment */
1259 	front_v->load_unload_ticks = 1;
1260 
1261 	assert(front_v->cargo_payment == nullptr);
1262 	/* One CargoPayment per vehicle and the vehicle limit equals the
1263 	 * limit in number of CargoPayments. Can't go wrong. */
1264 	static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1265 	assert(CargoPayment::CanAllocateItem());
1266 	front_v->cargo_payment = new CargoPayment(front_v);
1267 
1268 	StationIDStack next_station = front_v->GetNextStoppingStation();
1269 	if (front_v->orders.list == nullptr || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1270 		Station *st = Station::Get(front_v->last_station_visited);
1271 		for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1272 			const GoodsEntry *ge = &st->goods[v->cargo_type];
1273 			if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1274 				v->cargo.Stage(
1275 						HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1276 						front_v->last_station_visited, next_station,
1277 						front_v->current_order.GetUnloadType(), ge,
1278 						front_v->cargo_payment);
1279 				if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1280 			}
1281 		}
1282 	}
1283 }
1284 
1285 /**
1286  * Gets the amount of cargo the given vehicle can load in the current tick.
1287  * This is only about loading speed. The free capacity is ignored.
1288  * @param v Vehicle to be queried.
1289  * @return Amount of cargo the vehicle can load at once.
1290  */
GetLoadAmount(Vehicle * v)1291 static uint GetLoadAmount(Vehicle *v)
1292 {
1293 	const Engine *e = v->GetEngine();
1294 	uint load_amount = e->info.load_amount;
1295 
1296 	/* The default loadamount for mail is 1/4 of the load amount for passengers */
1297 	bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1298 	if (air_mail) load_amount = CeilDiv(load_amount, 4);
1299 
1300 	if (_settings_game.order.gradual_loading) {
1301 		uint16 cb_load_amount = CALLBACK_FAILED;
1302 		if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1303 			/* Use callback 36 */
1304 			cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1305 		} else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1306 			/* Use callback 12 */
1307 			cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1308 		}
1309 		if (cb_load_amount != CALLBACK_FAILED) {
1310 			if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1311 			if (cb_load_amount >= 0x100) {
1312 				ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1313 			} else if (cb_load_amount != 0) {
1314 				load_amount = cb_load_amount;
1315 			}
1316 		}
1317 	}
1318 
1319 	/* Scale load amount the same as capacity */
1320 	if (HasBit(e->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER) && !air_mail) load_amount = CeilDiv(load_amount * CargoSpec::Get(v->cargo_type)->multiplier, 0x100);
1321 
1322 	/* Zero load amount breaks a lot of things. */
1323 	return std::max(1u, load_amount);
1324 }
1325 
1326 /**
1327  * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1328  * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1329  * if that action does so. Otherwise return true.
1330  * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1331  * @param v First articulated part.
1332  * @param action Instance of Taction.
1333  * @return false if any of the action invocations returned false, true otherwise.
1334  */
1335 template<class Taction>
IterateVehicleParts(Vehicle * v,Taction action)1336 bool IterateVehicleParts(Vehicle *v, Taction action)
1337 {
1338 	for (Vehicle *w = v; w != nullptr;
1339 			w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1340 		if (!action(w)) return false;
1341 		if (w->type == VEH_TRAIN) {
1342 			Train *train = Train::From(w);
1343 			if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1344 		}
1345 	}
1346 	if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1347 	return true;
1348 }
1349 
1350 /**
1351  * Action to check if a vehicle has no stored cargo.
1352  */
1353 struct IsEmptyAction
1354 {
1355 	/**
1356 	 * Checks if the vehicle has stored cargo.
1357 	 * @param v Vehicle to be checked.
1358 	 * @return true if v is either empty or has only reserved cargo, false otherwise.
1359 	 */
operator ()IsEmptyAction1360 	bool operator()(const Vehicle *v)
1361 	{
1362 		return v->cargo.StoredCount() == 0;
1363 	}
1364 };
1365 
1366 /**
1367  * Refit preparation action.
1368  */
1369 struct PrepareRefitAction
1370 {
1371 	CargoArray &consist_capleft; ///< Capacities left in the consist.
1372 	CargoTypes &refit_mask;          ///< Bitmask of possible refit cargoes.
1373 
1374 	/**
1375 	 * Create a refit preparation action.
1376 	 * @param consist_capleft Capacities left in consist, to be updated here.
1377 	 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1378 	 */
PrepareRefitActionPrepareRefitAction1379 	PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) :
1380 		consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1381 
1382 	/**
1383 	 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1384 	 * adding the cargoes it can refit to to the refit mask.
1385 	 * @param v The vehicle to be refitted.
1386 	 * @return true.
1387 	 */
operator ()PrepareRefitAction1388 	bool operator()(const Vehicle *v)
1389 	{
1390 		this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1391 		this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1392 		return true;
1393 	}
1394 };
1395 
1396 /**
1397  * Action for returning reserved cargo.
1398  */
1399 struct ReturnCargoAction
1400 {
1401 	Station *st;        ///< Station to give the returned cargo to.
1402 	StationID next_hop; ///< Next hop the cargo should be assigned to.
1403 
1404 	/**
1405 	 * Construct a cargo return action.
1406 	 * @param st Station to give the returned cargo to.
1407 	 * @param next_one Next hop the cargo should be assigned to.
1408 	 */
ReturnCargoActionReturnCargoAction1409 	ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1410 
1411 	/**
1412 	 * Return all reserved cargo from a vehicle.
1413 	 * @param v Vehicle to return cargo from.
1414 	 * @return true.
1415 	 */
operator ()ReturnCargoAction1416 	bool operator()(Vehicle *v)
1417 	{
1418 		v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1419 		return true;
1420 	}
1421 };
1422 
1423 /**
1424  * Action for finalizing a refit.
1425  */
1426 struct FinalizeRefitAction
1427 {
1428 	CargoArray &consist_capleft;  ///< Capacities left in the consist.
1429 	Station *st;                  ///< Station to reserve cargo from.
1430 	StationIDStack &next_station; ///< Next hops to reserve cargo for.
1431 	bool do_reserve;              ///< If the vehicle should reserve.
1432 
1433 	/**
1434 	 * Create a finalizing action.
1435 	 * @param consist_capleft Capacities left in the consist.
1436 	 * @param st Station to reserve cargo from.
1437 	 * @param next_station Next hops to reserve cargo for.
1438 	 * @param do_reserve If we should reserve cargo or just add up the capacities.
1439 	 */
FinalizeRefitActionFinalizeRefitAction1440 	FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1441 		consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1442 
1443 	/**
1444 	 * Reserve cargo from the station and update the remaining consist capacities with the
1445 	 * vehicle's remaining free capacity.
1446 	 * @param v Vehicle to be finalized.
1447 	 * @return true.
1448 	 */
operator ()FinalizeRefitAction1449 	bool operator()(Vehicle *v)
1450 	{
1451 		if (this->do_reserve) {
1452 			this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1453 					&v->cargo, st->xy, this->next_station);
1454 		}
1455 		this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1456 		return true;
1457 	}
1458 };
1459 
1460 /**
1461  * Refit a vehicle in a station.
1462  * @param v Vehicle to be refitted.
1463  * @param consist_capleft Added cargo capacities in the consist.
1464  * @param st Station the vehicle is loading at.
1465  * @param next_station Possible next stations the vehicle can travel to.
1466  * @param new_cid Target cargo for refit.
1467  */
HandleStationRefit(Vehicle * v,CargoArray & consist_capleft,Station * st,StationIDStack next_station,CargoID new_cid)1468 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1469 {
1470 	Vehicle *v_start = v->GetFirstEnginePart();
1471 	if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1472 
1473 	Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1474 
1475 	CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1476 
1477 	/* Remove old capacity from consist capacity and collect refit mask. */
1478 	IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1479 
1480 	bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1481 	if (is_auto_refit) {
1482 		/* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1483 		new_cid = v_start->cargo_type;
1484 		for (CargoID cid : SetCargoBitIterator(refit_mask)) {
1485 			if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1486 				/* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1487 				 * the returned refit capacity will be greater than zero. */
1488 				DoCommand(v_start->tile, v_start->index, cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1489 				/* Try to balance different loadable cargoes between parts of the consist, so that
1490 				 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1491 				 * to the first loadable cargo for which there is only one packet. If the capacities
1492 				 * are equal refit to the cargo of which most is available. This is important for
1493 				 * consists of only a single vehicle as those will generally have a consist_capleft
1494 				 * of 0 for all cargoes. */
1495 				if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1496 						(consist_capleft[cid] == consist_capleft[new_cid] &&
1497 						st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1498 					new_cid = cid;
1499 				}
1500 			}
1501 		}
1502 	}
1503 
1504 	/* Refit if given a valid cargo. */
1505 	if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1506 		/* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1507 		 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1508 		 * "via any station" before reserving. We rather produce some more "any station" cargo than
1509 		 * misrouting it. */
1510 		IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1511 		CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1512 		if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1513 	}
1514 
1515 	/* Add new capacity to consist capacity and reserve cargo */
1516 	IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1517 			is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1518 
1519 	cur_company.Restore();
1520 }
1521 
1522 /**
1523  * Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.
1524  * @param st Station with cargo waiting to be loaded.
1525  * @param v Vehicle loading the cargo.
1526  * @return true when a vehicle can load the cargo.
1527  */
MayLoadUnderExclusiveRights(const Station * st,const Vehicle * v)1528 static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1529 {
1530 	return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1531 }
1532 
1533 struct ReserveCargoAction {
1534 	Station *st;
1535 	StationIDStack *next_station;
1536 
ReserveCargoActionReserveCargoAction1537 	ReserveCargoAction(Station *st, StationIDStack *next_station) :
1538 		st(st), next_station(next_station) {}
1539 
operator ()ReserveCargoAction1540 	bool operator()(Vehicle *v)
1541 	{
1542 		if (v->cargo_cap > v->cargo.RemainingCount() && MayLoadUnderExclusiveRights(st, v)) {
1543 			st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1544 					&v->cargo, st->xy, *next_station);
1545 		}
1546 
1547 		return true;
1548 	}
1549 
1550 };
1551 
1552 /**
1553  * Reserves cargo if the full load order and improved_load is set or if the
1554  * current order allows autorefit.
1555  * @param st Station where the consist is loading at the moment.
1556  * @param u Front of the loading vehicle consist.
1557  * @param consist_capleft If given, save free capacities after reserving there.
1558  * @param next_station Station(s) the vehicle will stop at next.
1559  */
ReserveConsist(Station * st,Vehicle * u,CargoArray * consist_capleft,StationIDStack * next_station)1560 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1561 {
1562 	/* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1563 	 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1564 	 * a vehicle belongs to already has the right cargo. */
1565 	bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1566 	for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1567 		assert(v->cargo_cap >= v->cargo.RemainingCount());
1568 
1569 		/* Exclude various ways in which the vehicle might not be the head of an equivalent of
1570 		 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1571 		 * to a different cargo and hasn't tried to do so, yet. */
1572 		if (!v->IsArticulatedPart() &&
1573 				(v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1574 				(v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1575 				(must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1576 			IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1577 		}
1578 		if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1579 		(*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1580 	}
1581 }
1582 
1583 /**
1584  * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1585  * again. Adjust for overhang of trains and set it at least to 1.
1586  * @param front The vehicle to be updated.
1587  * @param st The station the vehicle is loading at.
1588  * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1589  */
UpdateLoadUnloadTicks(Vehicle * front,const Station * st,int ticks)1590 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1591 {
1592 	if (front->type == VEH_TRAIN) {
1593 		/* Each platform tile is worth 2 rail vehicles. */
1594 		int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1595 		if (overhang > 0) {
1596 			ticks <<= 1;
1597 			ticks += (overhang * ticks) / 8;
1598 		}
1599 	}
1600 	/* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1601 	front->load_unload_ticks = std::max(1, ticks);
1602 }
1603 
1604 /**
1605  * Loads/unload the vehicle if possible.
1606  * @param front the vehicle to be (un)loaded
1607  */
LoadUnloadVehicle(Vehicle * front)1608 static void LoadUnloadVehicle(Vehicle *front)
1609 {
1610 	assert(front->current_order.IsType(OT_LOADING));
1611 
1612 	StationID last_visited = front->last_station_visited;
1613 	Station *st = Station::Get(last_visited);
1614 
1615 	StationIDStack next_station = front->GetNextStoppingStation();
1616 	bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1617 	CargoArray consist_capleft;
1618 	if (_settings_game.order.improved_load && use_autorefit ?
1619 			front->cargo_payment == nullptr : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1620 		ReserveConsist(st, front,
1621 				(use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1622 				&next_station);
1623 	}
1624 
1625 	/* We have not waited enough time till the next round of loading/unloading */
1626 	if (front->load_unload_ticks != 0) return;
1627 
1628 	if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1629 		/* The train reversed in the station. Take the "easy" way
1630 		 * out and let the train just leave as it always did. */
1631 		SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1632 		front->load_unload_ticks = 1;
1633 		return;
1634 	}
1635 
1636 	int new_load_unload_ticks = 0;
1637 	bool dirty_vehicle = false;
1638 	bool dirty_station = false;
1639 
1640 	bool completely_emptied = true;
1641 	bool anything_unloaded  = false;
1642 	bool anything_loaded    = false;
1643 	CargoTypes full_load_amount = 0;
1644 	CargoTypes cargo_not_full   = 0;
1645 	CargoTypes cargo_full       = 0;
1646 	CargoTypes reservation_left = 0;
1647 
1648 	front->cur_speed = 0;
1649 
1650 	CargoPayment *payment = front->cargo_payment;
1651 
1652 	uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1653 	for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1654 		if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1655 		if (v->cargo_cap == 0) continue;
1656 		artic_part++;
1657 
1658 		GoodsEntry *ge = &st->goods[v->cargo_type];
1659 
1660 		if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1661 			uint cargo_count = v->cargo.UnloadCount();
1662 			uint amount_unloaded = _settings_game.order.gradual_loading ? std::min(cargo_count, GetLoadAmount(v)) : cargo_count;
1663 			bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1664 
1665 			assert(payment != nullptr);
1666 			payment->SetCargo(v->cargo_type);
1667 
1668 			if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1669 				/* The station does not accept our goods anymore. */
1670 				if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1671 					/* Transfer instead of delivering. */
1672 					v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1673 							v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1674 				} else {
1675 					uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1676 					if (v->cargo_cap < new_remaining) {
1677 						/* Return some of the reserved cargo to not overload the vehicle. */
1678 						v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1679 					}
1680 
1681 					/* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1682 					v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1683 							v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1684 
1685 					/* ... say we unloaded something, otherwise we'll think we didn't unload
1686 					 * something and we didn't load something, so we must be finished
1687 					 * at this station. Setting the unloaded means that we will get a
1688 					 * retry for loading in the next cycle. */
1689 					anything_unloaded = true;
1690 				}
1691 			}
1692 
1693 			if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1694 				/* Mark the station dirty if we transfer, but not if we only deliver. */
1695 				dirty_station = true;
1696 
1697 				if (!ge->HasRating()) {
1698 					/* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1699 					 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1700 					ge->time_since_pickup = 0;
1701 					SetBit(ge->status, GoodsEntry::GES_RATING);
1702 				}
1703 			}
1704 
1705 			amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1706 			remaining = v->cargo.UnloadCount() > 0;
1707 			if (amount_unloaded > 0) {
1708 				dirty_vehicle = true;
1709 				anything_unloaded = true;
1710 				new_load_unload_ticks += amount_unloaded;
1711 
1712 				/* Deliver goods to the station */
1713 				st->time_since_unload = 0;
1714 			}
1715 
1716 			if (_settings_game.order.gradual_loading && remaining) {
1717 				completely_emptied = false;
1718 			} else {
1719 				/* We have finished unloading (cargo count == 0) */
1720 				ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1721 			}
1722 
1723 			continue;
1724 		}
1725 
1726 		/* Do not pick up goods when we have no-load set or loading is stopped. */
1727 		if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1728 
1729 		/* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1730 		if (front->current_order.IsRefit() && artic_part == 1) {
1731 			HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1732 			ge = &st->goods[v->cargo_type];
1733 		}
1734 
1735 		/* As we're loading here the following link can carry the full capacity of the vehicle. */
1736 		v->refit_cap = v->cargo_cap;
1737 
1738 		/* update stats */
1739 		int t;
1740 		switch (front->type) {
1741 			case VEH_TRAIN:
1742 			case VEH_SHIP:
1743 				t = front->vcache.cached_max_speed;
1744 				break;
1745 
1746 			case VEH_ROAD:
1747 				t = front->vcache.cached_max_speed / 2;
1748 				break;
1749 
1750 			case VEH_AIRCRAFT:
1751 				t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1752 				break;
1753 
1754 			default: NOT_REACHED();
1755 		}
1756 
1757 		/* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1758 		ge->last_speed = std::min(t, 255);
1759 		ge->last_age = std::min(_cur_year - front->build_year, 255);
1760 
1761 		assert(v->cargo_cap >= v->cargo.StoredCount());
1762 		/* Capacity available for loading more cargo. */
1763 		uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1764 
1765 		if (cap_left > 0) {
1766 			/* If vehicle can load cargo, reset time_since_pickup. */
1767 			ge->time_since_pickup = 0;
1768 
1769 			/* If there's goods waiting at the station, and the vehicle
1770 			 * has capacity for it, load it on the vehicle. */
1771 			if ((v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1772 				if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1773 				if (_settings_game.order.gradual_loading) cap_left = std::min(cap_left, GetLoadAmount(v));
1774 
1775 				uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1776 				if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1777 					/* Remember if there are reservations left so that we don't stop
1778 					 * loading before they're loaded. */
1779 					SetBit(reservation_left, v->cargo_type);
1780 				}
1781 
1782 				/* Store whether the maximum possible load amount was loaded or not.*/
1783 				if (loaded == cap_left) {
1784 					SetBit(full_load_amount, v->cargo_type);
1785 				} else {
1786 					ClrBit(full_load_amount, v->cargo_type);
1787 				}
1788 
1789 				/* TODO: Regarding this, when we do gradual loading, we
1790 				 * should first unload all vehicles and then start
1791 				 * loading them. Since this will cause
1792 				 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1793 				 * the whole vehicle chain is really totally empty, the
1794 				 * completely_emptied assignment can then be safely
1795 				 * removed; that's how TTDPatch behaves too. --pasky */
1796 				if (loaded > 0) {
1797 					completely_emptied = false;
1798 					anything_loaded = true;
1799 
1800 					st->time_since_load = 0;
1801 					st->last_vehicle_type = v->type;
1802 
1803 					if (ge->cargo.TotalCount() == 0) {
1804 						TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1805 						TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1806 						AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1807 					}
1808 
1809 					new_load_unload_ticks += loaded;
1810 
1811 					dirty_vehicle = dirty_station = true;
1812 				}
1813 			}
1814 		}
1815 
1816 		if (v->cargo.StoredCount() >= v->cargo_cap) {
1817 			SetBit(cargo_full, v->cargo_type);
1818 		} else {
1819 			SetBit(cargo_not_full, v->cargo_type);
1820 		}
1821 	}
1822 
1823 	if (anything_loaded || anything_unloaded) {
1824 		if (front->type == VEH_TRAIN) {
1825 			TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1826 			TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1827 		}
1828 	}
1829 
1830 	/* Only set completely_emptied, if we just unloaded all remaining cargo */
1831 	completely_emptied &= anything_unloaded;
1832 
1833 	if (!anything_unloaded) delete payment;
1834 
1835 	ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1836 	if (anything_loaded || anything_unloaded) {
1837 		if (_settings_game.order.gradual_loading) {
1838 			/* The time it takes to load one 'slice' of cargo or passengers depends
1839 			 * on the vehicle type - the values here are those found in TTDPatch */
1840 			const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1841 
1842 			new_load_unload_ticks = gradual_loading_wait_time[front->type];
1843 		}
1844 		/* We loaded less cargo than possible for all cargo types and it's not full
1845 		 * load and we're not supposed to wait any longer: stop loading. */
1846 		if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1847 				front->current_order_time >= (uint)std::max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1848 			SetBit(front->vehicle_flags, VF_STOP_LOADING);
1849 		}
1850 
1851 		UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1852 	} else {
1853 		UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1854 		bool finished_loading = true;
1855 		if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1856 			if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1857 				/* if the aircraft carries passengers and is NOT full, then
1858 				 * continue loading, no matter how much mail is in */
1859 				if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1860 						(cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1861 					finished_loading = false;
1862 				}
1863 			} else if (cargo_not_full != 0) {
1864 				finished_loading = false;
1865 			}
1866 
1867 			/* Refresh next hop stats if we're full loading to make the links
1868 			 * known to the distribution algorithm and allow cargo to be sent
1869 			 * along them. Otherwise the vehicle could wait for cargo
1870 			 * indefinitely if it hasn't visited the other links yet, or if the
1871 			 * links die while it's loading. */
1872 			if (!finished_loading) LinkRefresher::Run(front, true, true);
1873 		}
1874 
1875 		SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1876 	}
1877 
1878 	/* Calculate the loading indicator fill percent and display
1879 	 * In the Game Menu do not display indicators
1880 	 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1881 	 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1882 	 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1883 	 */
1884 	if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1885 		StringID percent_up_down = STR_NULL;
1886 		int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1887 		if (front->fill_percent_te_id == INVALID_TE_ID) {
1888 			front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1889 		} else {
1890 			UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1891 		}
1892 	}
1893 
1894 	if (completely_emptied) {
1895 		/* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1896 		 * properties such as weight, power and TE whenever the trigger runs. */
1897 		dirty_vehicle = true;
1898 		TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1899 	}
1900 
1901 	if (dirty_vehicle) {
1902 		SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
1903 		SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1904 		front->MarkDirty();
1905 	}
1906 	if (dirty_station) {
1907 		st->MarkTilesDirty(true);
1908 		SetWindowDirty(WC_STATION_VIEW, last_visited);
1909 		InvalidateWindowData(WC_STATION_LIST, last_visited);
1910 	}
1911 }
1912 
1913 /**
1914  * Load/unload the vehicles in this station according to the order
1915  * they entered.
1916  * @param st the station to do the loading/unloading for
1917  */
LoadUnloadStation(Station * st)1918 void LoadUnloadStation(Station *st)
1919 {
1920 	/* No vehicle is here... */
1921 	if (st->loading_vehicles.empty()) return;
1922 
1923 	Vehicle *last_loading = nullptr;
1924 	std::list<Vehicle *>::iterator iter;
1925 
1926 	/* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1927 	for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1928 		Vehicle *v = *iter;
1929 
1930 		if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1931 
1932 		assert(v->load_unload_ticks != 0);
1933 		if (--v->load_unload_ticks == 0) last_loading = v;
1934 	}
1935 
1936 	/* We only need to reserve and load/unload up to the last loading vehicle.
1937 	 * Anything else will be forgotten anyway after returning from this function.
1938 	 *
1939 	 * Especially this means we do _not_ need to reserve cargo for a single
1940 	 * consist in a station which is not allowed to load yet because its
1941 	 * load_unload_ticks is still not 0.
1942 	 */
1943 	if (last_loading == nullptr) return;
1944 
1945 	for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1946 		Vehicle *v = *iter;
1947 		if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1948 		if (v == last_loading) break;
1949 	}
1950 
1951 	/* Call the production machinery of industries */
1952 	for (Industry *iid : _cargo_delivery_destinations) {
1953 		TriggerIndustryProduction(iid);
1954 	}
1955 	_cargo_delivery_destinations.clear();
1956 }
1957 
1958 /**
1959  * Monthly update of the economic data (of the companies as well as economic fluctuations).
1960  */
CompaniesMonthlyLoop()1961 void CompaniesMonthlyLoop()
1962 {
1963 	CompaniesGenStatistics();
1964 	if (_settings_game.economy.inflation) {
1965 		AddInflation();
1966 		RecomputePrices();
1967 	}
1968 	CompaniesPayInterest();
1969 	HandleEconomyFluctuations();
1970 }
1971 
DoAcquireCompany(Company * c)1972 static void DoAcquireCompany(Company *c)
1973 {
1974 	CompanyID ci = c->index;
1975 
1976 	CompanyNewsInformation *cni = new CompanyNewsInformation(c, Company::Get(_current_company));
1977 
1978 	SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1979 	SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1980 	SetDParamStr(2, cni->company_name);
1981 	SetDParamStr(3, cni->other_company_name);
1982 	SetDParam(4, c->bankrupt_value);
1983 	AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1984 	AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1985 	Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1986 
1987 	ChangeOwnershipOfCompanyItems(ci, _current_company);
1988 
1989 	if (c->bankrupt_value == 0) {
1990 		Company *owner = Company::Get(_current_company);
1991 
1992 		/* Get both the balance and the loan of the company you just bought. */
1993 		SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, -c->money));
1994 		owner->current_loan += c->current_loan;
1995 	}
1996 
1997 	if (c->is_ai) AI::Stop(c->index);
1998 
1999 	CloseCompanyWindows(ci);
2000 	InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2001 	InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
2002 	InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
2003 	InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
2004 
2005 	delete c;
2006 }
2007 
2008 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2009 
2010 /**
2011  * Acquire shares in an opposing company.
2012  * @param tile unused
2013  * @param flags type of operation
2014  * @param p1 company to buy the shares from
2015  * @param p2 unused
2016  * @param text unused
2017  * @return the cost of this operation or an error
2018  */
CmdBuyShareInCompany(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2019 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2020 {
2021 	CommandCost cost(EXPENSES_OTHER);
2022 	CompanyID target_company = (CompanyID)p1;
2023 	Company *c = Company::GetIfValid(target_company);
2024 
2025 	/* Check if buying shares is allowed (protection against modified clients)
2026 	 * Cannot buy own shares */
2027 	if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2028 
2029 	/* Protect new companies from hostile takeovers */
2030 	if (_cur_year - c->inaugurated_year < _settings_game.economy.min_years_for_shares) return_cmd_error(STR_ERROR_PROTECTED);
2031 
2032 	/* Those lines are here for network-protection (clients can be slow) */
2033 	if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2034 
2035 	if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2036 		if (!c->is_ai) return cost; //  We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2037 
2038 		if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2039 	}
2040 
2041 
2042 	cost.AddCost(CalculateCompanyValue(c) >> 2);
2043 	if (flags & DC_EXEC) {
2044 		Owner *b = c->share_owners;
2045 
2046 		while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2047 		*b = _current_company;
2048 
2049 		for (int i = 0; c->share_owners[i] == _current_company;) {
2050 			if (++i == 4) {
2051 				c->bankrupt_value = 0;
2052 				DoAcquireCompany(c);
2053 				break;
2054 			}
2055 		}
2056 		InvalidateWindowData(WC_COMPANY, target_company);
2057 		CompanyAdminUpdate(c);
2058 	}
2059 	return cost;
2060 }
2061 
2062 /**
2063  * Sell shares in an opposing company.
2064  * @param tile unused
2065  * @param flags type of operation
2066  * @param p1 company to sell the shares from
2067  * @param p2 unused
2068  * @param text unused
2069  * @return the cost of this operation or an error
2070  */
CmdSellShareInCompany(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2071 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2072 {
2073 	CompanyID target_company = (CompanyID)p1;
2074 	Company *c = Company::GetIfValid(target_company);
2075 
2076 	/* Cannot sell own shares */
2077 	if (c == nullptr || _current_company == target_company) return CMD_ERROR;
2078 
2079 	/* Check if selling shares is allowed (protection against modified clients).
2080 	 * However, we must sell shares of companies being closed down. */
2081 	if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2082 
2083 	/* Those lines are here for network-protection (clients can be slow) */
2084 	if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2085 
2086 	/* adjust it a little to make it less profitable to sell and buy */
2087 	Money cost = CalculateCompanyValue(c) >> 2;
2088 	cost = -(cost - (cost >> 7));
2089 
2090 	if (flags & DC_EXEC) {
2091 		Owner *b = c->share_owners;
2092 		while (*b != _current_company) b++; // share owners is guaranteed to contain company
2093 		*b = COMPANY_SPECTATOR;
2094 		InvalidateWindowData(WC_COMPANY, target_company);
2095 		CompanyAdminUpdate(c);
2096 	}
2097 	return CommandCost(EXPENSES_OTHER, cost);
2098 }
2099 
2100 /**
2101  * Buy up another company.
2102  * When a competing company is gone bankrupt you get the chance to purchase
2103  * that company.
2104  * @todo currently this only works for AI companies
2105  * @param tile unused
2106  * @param flags type of operation
2107  * @param p1 company to buy up
2108  * @param p2 unused
2109  * @param text unused
2110  * @return the cost of this operation or an error
2111  */
CmdBuyCompany(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2112 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2113 {
2114 	CompanyID target_company = (CompanyID)p1;
2115 	Company *c = Company::GetIfValid(target_company);
2116 	if (c == nullptr) return CMD_ERROR;
2117 
2118 	/* Disable takeovers when not asked */
2119 	if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2120 
2121 	/* Disable taking over the local company in singleplayer mode */
2122 	if (!_networking && _local_company == c->index) return CMD_ERROR;
2123 
2124 	/* Do not allow companies to take over themselves */
2125 	if (target_company == _current_company) return CMD_ERROR;
2126 
2127 	/* Disable taking over when not allowed. */
2128 	if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2129 
2130 	/* Get the cost here as the company is deleted in DoAcquireCompany. */
2131 	CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2132 
2133 	if (flags & DC_EXEC) {
2134 		DoAcquireCompany(c);
2135 	}
2136 	return cost;
2137 }
2138