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 station_cmd.cpp Handling of station tiles. */
9 
10 #include "stdafx.h"
11 #include "aircraft.h"
12 #include "bridge_map.h"
13 #include "cmd_helper.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "command_func.h"
17 #include "town.h"
18 #include "news_func.h"
19 #include "train.h"
20 #include "ship.h"
21 #include "roadveh.h"
22 #include "industry.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
30 #include "water.h"
31 #include "strings_func.h"
32 #include "clear_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "station_func.h"
40 #include "station_kdtree.h"
41 #include "roadstop_base.h"
42 #include "newgrf_railtype.h"
43 #include "newgrf_roadtype.h"
44 #include "waypoint_base.h"
45 #include "waypoint_func.h"
46 #include "pbs.h"
47 #include "debug.h"
48 #include "core/random_func.hpp"
49 #include "company_base.h"
50 #include "table/airporttile_ids.h"
51 #include "newgrf_airporttiles.h"
52 #include "order_backup.h"
53 #include "newgrf_house.h"
54 #include "company_gui.h"
55 #include "linkgraph/linkgraph_base.h"
56 #include "linkgraph/refresh.h"
57 #include "widgets/station_widget.h"
58 #include "tunnelbridge_map.h"
59 
60 #include "table/strings.h"
61 
62 #include "safeguards.h"
63 
64 /**
65  * Static instance of FlowStat::SharesMap.
66  * Note: This instance is created on task start.
67  *       Lazy creation on first usage results in a data race between the CDist threads.
68  */
69 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
70 
71 /**
72  * Check whether the given tile is a hangar.
73  * @param t the tile to of whether it is a hangar.
74  * @pre IsTileType(t, MP_STATION)
75  * @return true if and only if the tile is a hangar.
76  */
IsHangar(TileIndex t)77 bool IsHangar(TileIndex t)
78 {
79 	assert(IsTileType(t, MP_STATION));
80 
81 	/* If the tile isn't an airport there's no chance it's a hangar. */
82 	if (!IsAirport(t)) return false;
83 
84 	const Station *st = Station::GetByTile(t);
85 	const AirportSpec *as = st->airport.GetSpec();
86 
87 	for (uint i = 0; i < as->nof_depots; i++) {
88 		if (st->airport.GetHangarTile(i) == t) return true;
89 	}
90 
91 	return false;
92 }
93 
94 /**
95  * Look for a station owned by the given company around the given tile area.
96  * @param ta the area to search over
97  * @param closest_station the closest owned station found so far
98  * @param company the company whose stations to look for
99  * @param st to 'return' the found station
100  * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
101  */
102 template <class T>
GetStationAround(TileArea ta,StationID closest_station,CompanyID company,T ** st)103 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
104 {
105 	ta.Expand(1);
106 
107 	/* check around to see if there are any stations there owned by the company */
108 	for (TileIndex tile_cur : ta) {
109 		if (IsTileType(tile_cur, MP_STATION)) {
110 			StationID t = GetStationIndex(tile_cur);
111 			if (!T::IsValidID(t) || Station::Get(t)->owner != company) continue;
112 			if (closest_station == INVALID_STATION) {
113 				closest_station = t;
114 			} else if (closest_station != t) {
115 				return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
116 			}
117 		}
118 	}
119 	*st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
120 	return CommandCost();
121 }
122 
123 /**
124  * Function to check whether the given tile matches some criterion.
125  * @param tile the tile to check
126  * @return true if it matches, false otherwise
127  */
128 typedef bool (*CMSAMatcher)(TileIndex tile);
129 
130 /**
131  * Counts the numbers of tiles matching a specific type in the area around
132  * @param tile the center tile of the 'count area'
133  * @param cmp the comparator/matcher (@see CMSAMatcher)
134  * @return the number of matching tiles around
135  */
CountMapSquareAround(TileIndex tile,CMSAMatcher cmp)136 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
137 {
138 	int num = 0;
139 
140 	for (int dx = -3; dx <= 3; dx++) {
141 		for (int dy = -3; dy <= 3; dy++) {
142 			TileIndex t = TileAddWrap(tile, dx, dy);
143 			if (t != INVALID_TILE && cmp(t)) num++;
144 		}
145 	}
146 
147 	return num;
148 }
149 
150 /**
151  * Check whether the tile is a mine.
152  * @param tile the tile to investigate.
153  * @return true if and only if the tile is a mine
154  */
CMSAMine(TileIndex tile)155 static bool CMSAMine(TileIndex tile)
156 {
157 	/* No industry */
158 	if (!IsTileType(tile, MP_INDUSTRY)) return false;
159 
160 	const Industry *ind = Industry::GetByTile(tile);
161 
162 	/* No extractive industry */
163 	if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
164 
165 	for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
166 		/* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
167 		 * Also the production of passengers and mail is ignored. */
168 		if (ind->produced_cargo[i] != CT_INVALID &&
169 				(CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
170 			return true;
171 		}
172 	}
173 
174 	return false;
175 }
176 
177 /**
178  * Check whether the tile is water.
179  * @param tile the tile to investigate.
180  * @return true if and only if the tile is a water tile
181  */
CMSAWater(TileIndex tile)182 static bool CMSAWater(TileIndex tile)
183 {
184 	return IsTileType(tile, MP_WATER) && IsWater(tile);
185 }
186 
187 /**
188  * Check whether the tile is a tree.
189  * @param tile the tile to investigate.
190  * @return true if and only if the tile is a tree tile
191  */
CMSATree(TileIndex tile)192 static bool CMSATree(TileIndex tile)
193 {
194 	return IsTileType(tile, MP_TREES);
195 }
196 
197 #define M(x) ((x) - STR_SV_STNAME)
198 
199 enum StationNaming {
200 	STATIONNAMING_RAIL,
201 	STATIONNAMING_ROAD,
202 	STATIONNAMING_AIRPORT,
203 	STATIONNAMING_OILRIG,
204 	STATIONNAMING_DOCK,
205 	STATIONNAMING_HELIPORT,
206 };
207 
208 /** Information to handle station action 0 property 24 correctly */
209 struct StationNameInformation {
210 	uint32 free_names; ///< Current bitset of free names (we can remove names).
211 	bool *indtypes;    ///< Array of bools telling whether an industry type has been found.
212 };
213 
214 /**
215  * Find a station action 0 property 24 station name, or reduce the
216  * free_names if needed.
217  * @param tile the tile to search
218  * @param user_data the StationNameInformation to base the search on
219  * @return true if the tile contains an industry that has not given
220  *              its name to one of the other stations in town.
221  */
FindNearIndustryName(TileIndex tile,void * user_data)222 static bool FindNearIndustryName(TileIndex tile, void *user_data)
223 {
224 	/* All already found industry types */
225 	StationNameInformation *sni = (StationNameInformation*)user_data;
226 	if (!IsTileType(tile, MP_INDUSTRY)) return false;
227 
228 	/* If the station name is undefined it means that it doesn't name a station */
229 	IndustryType indtype = GetIndustryType(tile);
230 	if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
231 
232 	/* In all cases if an industry that provides a name is found two of
233 	 * the standard names will be disabled. */
234 	sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
235 	return !sni->indtypes[indtype];
236 }
237 
GenerateStationName(Station * st,TileIndex tile,StationNaming name_class)238 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
239 {
240 	static const uint32 _gen_station_name_bits[] = {
241 		0,                                       // STATIONNAMING_RAIL
242 		0,                                       // STATIONNAMING_ROAD
243 		1U << M(STR_SV_STNAME_AIRPORT),          // STATIONNAMING_AIRPORT
244 		1U << M(STR_SV_STNAME_OILFIELD),         // STATIONNAMING_OILRIG
245 		1U << M(STR_SV_STNAME_DOCKS),            // STATIONNAMING_DOCK
246 		1U << M(STR_SV_STNAME_HELIPORT),         // STATIONNAMING_HELIPORT
247 	};
248 
249 	const Town *t = st->town;
250 	uint32 free_names = UINT32_MAX;
251 
252 	bool indtypes[NUM_INDUSTRYTYPES];
253 	memset(indtypes, 0, sizeof(indtypes));
254 
255 	for (const Station *s : Station::Iterate()) {
256 		if (s != st && s->town == t) {
257 			if (s->indtype != IT_INVALID) {
258 				indtypes[s->indtype] = true;
259 				StringID name = GetIndustrySpec(s->indtype)->station_name;
260 				if (name != STR_UNDEFINED) {
261 					/* Filter for other industrytypes with the same name */
262 					for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
263 						const IndustrySpec *indsp = GetIndustrySpec(it);
264 						if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
265 					}
266 				}
267 				continue;
268 			}
269 			uint str = M(s->string_id);
270 			if (str <= 0x20) {
271 				if (str == M(STR_SV_STNAME_FOREST)) {
272 					str = M(STR_SV_STNAME_WOODS);
273 				}
274 				ClrBit(free_names, str);
275 			}
276 		}
277 	}
278 
279 	TileIndex indtile = tile;
280 	StationNameInformation sni = { free_names, indtypes };
281 	if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
282 		/* An industry has been found nearby */
283 		IndustryType indtype = GetIndustryType(indtile);
284 		const IndustrySpec *indsp = GetIndustrySpec(indtype);
285 		/* STR_NULL means it only disables oil rig/mines */
286 		if (indsp->station_name != STR_NULL) {
287 			st->indtype = indtype;
288 			return STR_SV_STNAME_FALLBACK;
289 		}
290 	}
291 
292 	/* Oil rigs/mines name could be marked not free by looking for a near by industry. */
293 	free_names = sni.free_names;
294 
295 	/* check default names */
296 	uint32 tmp = free_names & _gen_station_name_bits[name_class];
297 	if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
298 
299 	/* check mine? */
300 	if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
301 		if (CountMapSquareAround(tile, CMSAMine) >= 2) {
302 			return STR_SV_STNAME_MINES;
303 		}
304 	}
305 
306 	/* check close enough to town to get central as name? */
307 	if (DistanceMax(tile, t->xy) < 8) {
308 		if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
309 
310 		if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
311 	}
312 
313 	/* Check lakeside */
314 	if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
315 			DistanceFromEdge(tile) < 20 &&
316 			CountMapSquareAround(tile, CMSAWater) >= 5) {
317 		return STR_SV_STNAME_LAKESIDE;
318 	}
319 
320 	/* Check woods */
321 	if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
322 				CountMapSquareAround(tile, CMSATree) >= 8 ||
323 				CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
324 			) {
325 		return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
326 	}
327 
328 	/* check elevation compared to town */
329 	int z = GetTileZ(tile);
330 	int z2 = GetTileZ(t->xy);
331 	if (z < z2) {
332 		if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
333 	} else if (z > z2) {
334 		if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
335 	}
336 
337 	/* check direction compared to town */
338 	static const int8 _direction_and_table[] = {
339 		~( (1 << M(STR_SV_STNAME_WEST))  | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
340 		~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
341 		~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
342 		~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
343 	};
344 
345 	free_names &= _direction_and_table[
346 		(TileX(tile) < TileX(t->xy)) +
347 		(TileY(tile) < TileY(t->xy)) * 2];
348 
349 	tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
350 	return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
351 }
352 #undef M
353 
354 /**
355  * Find the closest deleted station of the current company
356  * @param tile the tile to search from.
357  * @return the closest station or nullptr if too far.
358  */
GetClosestDeletedStation(TileIndex tile)359 static Station *GetClosestDeletedStation(TileIndex tile)
360 {
361 	uint threshold = 8;
362 
363 	Station *best_station = nullptr;
364 	ForAllStationsRadius(tile, threshold, [&](Station *st) {
365 		if (!st->IsInUse() && st->owner == _current_company) {
366 			uint cur_dist = DistanceManhattan(tile, st->xy);
367 
368 			if (cur_dist < threshold) {
369 				threshold = cur_dist;
370 				best_station = st;
371 			} else if (cur_dist == threshold && best_station != nullptr) {
372 				/* In case of a tie, lowest station ID wins */
373 				if (st->index < best_station->index) best_station = st;
374 			}
375 		}
376 	});
377 
378 	return best_station;
379 }
380 
381 
GetTileArea(TileArea * ta,StationType type) const382 void Station::GetTileArea(TileArea *ta, StationType type) const
383 {
384 	switch (type) {
385 		case STATION_RAIL:
386 			*ta = this->train_station;
387 			return;
388 
389 		case STATION_AIRPORT:
390 			*ta = this->airport;
391 			return;
392 
393 		case STATION_TRUCK:
394 			*ta = this->truck_station;
395 			return;
396 
397 		case STATION_BUS:
398 			*ta = this->bus_station;
399 			return;
400 
401 		case STATION_DOCK:
402 		case STATION_OILRIG:
403 			*ta = this->docking_station;
404 			return;
405 
406 		default: NOT_REACHED();
407 	}
408 }
409 
410 /**
411  * Update the virtual coords needed to draw the station sign.
412  */
UpdateVirtCoord()413 void Station::UpdateVirtCoord()
414 {
415 	Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
416 
417 	pt.y -= 32 * ZOOM_LVL_BASE;
418 	if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
419 
420 	if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
421 
422 	SetDParam(0, this->index);
423 	SetDParam(1, this->facilities);
424 	this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
425 
426 	_viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
427 
428 	SetWindowDirty(WC_STATION_VIEW, this->index);
429 }
430 
431 /**
432  * Move the station main coordinate somewhere else.
433  * @param new_xy new tile location of the sign
434  */
MoveSign(TileIndex new_xy)435 void Station::MoveSign(TileIndex new_xy)
436 {
437 	if (this->xy == new_xy) return;
438 
439 	_station_kdtree.Remove(this->index);
440 
441 	this->BaseStation::MoveSign(new_xy);
442 
443 	_station_kdtree.Insert(this->index);
444 }
445 
446 /** Update the virtual coords needed to draw the station sign for all stations. */
UpdateAllStationVirtCoords()447 void UpdateAllStationVirtCoords()
448 {
449 	for (BaseStation *st : BaseStation::Iterate()) {
450 		st->UpdateVirtCoord();
451 	}
452 }
453 
FillCachedName() const454 void BaseStation::FillCachedName() const
455 {
456 	char buf[MAX_LENGTH_STATION_NAME_CHARS * MAX_CHAR_LENGTH];
457 	int64 args_array[] = { this->index };
458 	StringParameters tmp_params(args_array);
459 	char *end = GetStringWithArgs(buf, Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, &tmp_params, lastof(buf));
460 	this->cached_name.assign(buf, end);
461 }
462 
ClearAllStationCachedNames()463 void ClearAllStationCachedNames()
464 {
465 	for (BaseStation *st : BaseStation::Iterate()) {
466 		st->cached_name.clear();
467 	}
468 }
469 
470 /**
471  * Get a mask of the cargo types that the station accepts.
472  * @param st Station to query
473  * @return the expected mask
474  */
GetAcceptanceMask(const Station * st)475 static CargoTypes GetAcceptanceMask(const Station *st)
476 {
477 	CargoTypes mask = 0;
478 
479 	for (CargoID i = 0; i < NUM_CARGO; i++) {
480 		if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, i);
481 	}
482 	return mask;
483 }
484 
485 /**
486  * Items contains the two cargo names that are to be accepted or rejected.
487  * msg is the string id of the message to display.
488  */
ShowRejectOrAcceptNews(const Station * st,uint num_items,CargoID * cargo,StringID msg)489 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
490 {
491 	for (uint i = 0; i < num_items; i++) {
492 		SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
493 	}
494 
495 	SetDParam(0, st->index);
496 	AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
497 }
498 
499 /**
500  * Get the cargo types being produced around the tile (in a rectangle).
501  * @param north_tile Northern most tile of area
502  * @param w X extent of the area
503  * @param h Y extent of the area
504  * @param rad Search radius in addition to the given area
505  */
GetProductionAroundTiles(TileIndex north_tile,int w,int h,int rad)506 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
507 {
508 	CargoArray produced;
509 	std::set<IndustryID> industries;
510 	TileArea ta = TileArea(north_tile, w, h).Expand(rad);
511 
512 	/* Loop over all tiles to get the produced cargo of
513 	 * everything except industries */
514 	for (TileIndex tile : ta) {
515 		if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
516 		AddProducedCargo(tile, produced);
517 	}
518 
519 	/* Loop over the seen industries. They produce cargo for
520 	 * anything that is within 'rad' of any one of their tiles.
521 	 */
522 	for (IndustryID industry : industries) {
523 		const Industry *i = Industry::Get(industry);
524 		/* Skip industry with neutral station */
525 		if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
526 
527 		for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
528 			CargoID cargo = i->produced_cargo[j];
529 			if (cargo != CT_INVALID) produced[cargo]++;
530 		}
531 	}
532 
533 	return produced;
534 }
535 
536 /**
537  * Get the acceptance of cargoes around the tile in 1/8.
538  * @param center_tile Center of the search area
539  * @param w X extent of area
540  * @param h Y extent of area
541  * @param rad Search radius in addition to given area
542  * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
543  * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
544  */
GetAcceptanceAroundTiles(TileIndex center_tile,int w,int h,int rad,CargoTypes * always_accepted)545 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
546 {
547 	CargoArray acceptance;
548 	if (always_accepted != nullptr) *always_accepted = 0;
549 
550 	TileArea ta = TileArea(center_tile, w, h).Expand(rad);
551 
552 	for (TileIndex tile : ta) {
553 		/* Ignore industry if it has a neutral station. */
554 		if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
555 
556 		AddAcceptedCargo(tile, acceptance, always_accepted);
557 	}
558 
559 	return acceptance;
560 }
561 
562 /**
563  * Get the acceptance of cargoes around the station in.
564  * @param st Station to get acceptance of.
565  * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
566  */
GetAcceptanceAroundStation(const Station * st,CargoTypes * always_accepted)567 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
568 {
569 	CargoArray acceptance;
570 	if (always_accepted != nullptr) *always_accepted = 0;
571 
572 	BitmapTileIterator it(st->catchment_tiles);
573 	for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
574 		AddAcceptedCargo(tile, acceptance, always_accepted);
575 	}
576 
577 	return acceptance;
578 }
579 
580 /**
581  * Update the acceptance for a station.
582  * @param st Station to update
583  * @param show_msg controls whether to display a message that acceptance was changed.
584  */
UpdateStationAcceptance(Station * st,bool show_msg)585 void UpdateStationAcceptance(Station *st, bool show_msg)
586 {
587 	/* old accepted goods types */
588 	CargoTypes old_acc = GetAcceptanceMask(st);
589 
590 	/* And retrieve the acceptance. */
591 	CargoArray acceptance;
592 	if (!st->rect.IsEmpty()) {
593 		acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
594 	}
595 
596 	/* Adjust in case our station only accepts fewer kinds of goods */
597 	for (CargoID i = 0; i < NUM_CARGO; i++) {
598 		uint amt = acceptance[i];
599 
600 		/* Make sure the station can accept the goods type. */
601 		bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
602 		if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
603 				(is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
604 			amt = 0;
605 		}
606 
607 		GoodsEntry &ge = st->goods[i];
608 		SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
609 		if (LinkGraph::IsValidID(ge.link_graph)) {
610 			(*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
611 		}
612 	}
613 
614 	/* Only show a message in case the acceptance was actually changed. */
615 	CargoTypes new_acc = GetAcceptanceMask(st);
616 	if (old_acc == new_acc) return;
617 
618 	/* show a message to report that the acceptance was changed? */
619 	if (show_msg && st->owner == _local_company && st->IsInUse()) {
620 		/* List of accept and reject strings for different number of
621 		 * cargo types */
622 		static const StringID accept_msg[] = {
623 			STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
624 			STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
625 		};
626 		static const StringID reject_msg[] = {
627 			STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
628 			STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
629 		};
630 
631 		/* Array of accepted and rejected cargo types */
632 		CargoID accepts[2] = { CT_INVALID, CT_INVALID };
633 		CargoID rejects[2] = { CT_INVALID, CT_INVALID };
634 		uint num_acc = 0;
635 		uint num_rej = 0;
636 
637 		/* Test each cargo type to see if its acceptance has changed */
638 		for (CargoID i = 0; i < NUM_CARGO; i++) {
639 			if (HasBit(new_acc, i)) {
640 				if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
641 					/* New cargo is accepted */
642 					accepts[num_acc++] = i;
643 				}
644 			} else {
645 				if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
646 					/* Old cargo is no longer accepted */
647 					rejects[num_rej++] = i;
648 				}
649 			}
650 		}
651 
652 		/* Show news message if there are any changes */
653 		if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
654 		if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
655 	}
656 
657 	/* redraw the station view since acceptance changed */
658 	SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
659 }
660 
UpdateStationSignCoord(BaseStation * st)661 static void UpdateStationSignCoord(BaseStation *st)
662 {
663 	const StationRect *r = &st->rect;
664 
665 	if (r->IsEmpty()) return; // no tiles belong to this station
666 
667 	/* clamp sign coord to be inside the station rect */
668 	TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
669 	st->MoveSign(new_xy);
670 
671 	if (!Station::IsExpected(st)) return;
672 	Station *full_station = Station::From(st);
673 	for (CargoID c = 0; c < NUM_CARGO; ++c) {
674 		LinkGraphID lg = full_station->goods[c].link_graph;
675 		if (!LinkGraph::IsValidID(lg)) continue;
676 		(*LinkGraph::Get(lg))[full_station->goods[c].node].UpdateLocation(st->xy);
677 	}
678 }
679 
680 /**
681  * Common part of building various station parts and possibly attaching them to an existing one.
682  * @param[in,out] st Station to attach to
683  * @param flags Command flags
684  * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
685  * @param area Area occupied by the new part
686  * @param name_class Station naming class to use to generate the new station's name
687  * @return Command error that occurred, if any
688  */
BuildStationPart(Station ** st,DoCommandFlag flags,bool reuse,TileArea area,StationNaming name_class)689 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
690 {
691 	/* Find a deleted station close to us */
692 	if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
693 
694 	if (*st != nullptr) {
695 		if ((*st)->owner != _current_company) {
696 			return_cmd_error(CMD_ERROR);
697 		}
698 
699 		CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
700 		if (ret.Failed()) return ret;
701 	} else {
702 		/* allocate and initialize new station */
703 		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
704 
705 		if (flags & DC_EXEC) {
706 			*st = new Station(area.tile);
707 			_station_kdtree.Insert((*st)->index);
708 
709 			(*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
710 			(*st)->string_id = GenerateStationName(*st, area.tile, name_class);
711 
712 			if (Company::IsValidID(_current_company)) {
713 				SetBit((*st)->town->have_ratings, _current_company);
714 			}
715 		}
716 	}
717 	return CommandCost();
718 }
719 
720 /**
721  * This is called right after a station was deleted.
722  * It checks if the whole station is free of substations, and if so, the station will be
723  * deleted after a little while.
724  * @param st Station
725  */
DeleteStationIfEmpty(BaseStation * st)726 static void DeleteStationIfEmpty(BaseStation *st)
727 {
728 	if (!st->IsInUse()) {
729 		st->delete_ctr = 0;
730 		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
731 	}
732 	/* station remains but it probably lost some parts - station sign should stay in the station boundaries */
733 	UpdateStationSignCoord(st);
734 }
735 
736 /**
737  * After adding/removing tiles to station, update some station-related stuff.
738  * @param adding True if adding tiles, false if removing them.
739  * @param type StationType being modified.
740  */
AfterStationTileSetChange(bool adding,StationType type)741 void Station::AfterStationTileSetChange(bool adding, StationType type)
742 {
743 	this->UpdateVirtCoord();
744 	this->RecomputeCatchment();
745 	DirtyCompanyInfrastructureWindows(this->owner);
746 	if (adding) InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
747 
748 	switch (type) {
749 		case STATION_RAIL:
750 			SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
751 			break;
752 		case STATION_AIRPORT:
753 			break;
754 		case STATION_TRUCK:
755 		case STATION_BUS:
756 			SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
757 			break;
758 		case STATION_DOCK:
759 			SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
760 			break;
761 		default: NOT_REACHED();
762 	}
763 
764 	if (adding) {
765 		UpdateStationAcceptance(this, false);
766 		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
767 	} else {
768 		DeleteStationIfEmpty(this);
769 	}
770 
771 }
772 
773 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
774 
775 /**
776  * Checks if the given tile is buildable, flat and has a certain height.
777  * @param tile TileIndex to check.
778  * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
779  * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
780  * @param allow_steep Whether steep slopes are allowed.
781  * @param check_bridge Check for the existence of a bridge.
782  * @return The cost in case of success, or an error code if it failed.
783  */
CheckBuildableTile(TileIndex tile,uint invalid_dirs,int & allowed_z,bool allow_steep,bool check_bridge=true)784 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
785 {
786 	if (check_bridge && IsBridgeAbove(tile)) {
787 		return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
788 	}
789 
790 	CommandCost ret = EnsureNoVehicleOnGround(tile);
791 	if (ret.Failed()) return ret;
792 
793 	int z;
794 	Slope tileh = GetTileSlope(tile, &z);
795 
796 	/* Prohibit building if
797 	 *   1) The tile is "steep" (i.e. stretches two height levels).
798 	 *   2) The tile is non-flat and the build_on_slopes switch is disabled.
799 	 */
800 	if ((!allow_steep && IsSteepSlope(tileh)) ||
801 			((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
802 		return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
803 	}
804 
805 	CommandCost cost(EXPENSES_CONSTRUCTION);
806 	int flat_z = z + GetSlopeMaxZ(tileh);
807 	if (tileh != SLOPE_FLAT) {
808 		/* Forbid building if the tile faces a slope in a invalid direction. */
809 		for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
810 			if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
811 				return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
812 			}
813 		}
814 		cost.AddCost(_price[PR_BUILD_FOUNDATION]);
815 	}
816 
817 	/* The level of this tile must be equal to allowed_z. */
818 	if (allowed_z < 0) {
819 		/* First tile. */
820 		allowed_z = flat_z;
821 	} else if (allowed_z != flat_z) {
822 		return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
823 	}
824 
825 	return cost;
826 }
827 
828 /**
829  * Checks if an airport can be built at the given location and clear the area.
830  * @param tile_iter Airport tile iterator.
831  * @param flags Operation to perform.
832  * @return The cost in case of success, or an error code if it failed.
833  */
CheckFlatLandAirport(AirportTileTableIterator tile_iter,DoCommandFlag flags)834 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
835 {
836 	CommandCost cost(EXPENSES_CONSTRUCTION);
837 	int allowed_z = -1;
838 
839 	for (; tile_iter != INVALID_TILE; ++tile_iter) {
840 		CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
841 		if (ret.Failed()) return ret;
842 		cost.AddCost(ret);
843 
844 		ret = DoCommand(tile_iter, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
845 		if (ret.Failed()) return ret;
846 		cost.AddCost(ret);
847 	}
848 
849 	return cost;
850 }
851 
852 /**
853  * Checks if a rail station can be built at the given area.
854  * @param tile_area Area to check.
855  * @param flags Operation to perform.
856  * @param axis Rail station axis.
857  * @param station StationID to be queried and returned if available.
858  * @param rt The rail type to check for (overbuilding rail stations over rail).
859  * @param affected_vehicles List of trains with PBS reservations on the tiles
860  * @param spec_class Station class.
861  * @param spec_index Index into the station class.
862  * @param plat_len Platform length.
863  * @param numtracks Number of platforms.
864  * @return The cost in case of success, or an error code if it failed.
865  */
CheckFlatLandRailStation(TileArea tile_area,DoCommandFlag flags,Axis axis,StationID * station,RailType rt,std::vector<Train * > & affected_vehicles,StationClassID spec_class,byte spec_index,byte plat_len,byte numtracks)866 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
867 {
868 	CommandCost cost(EXPENSES_CONSTRUCTION);
869 	int allowed_z = -1;
870 	uint invalid_dirs = 5 << axis;
871 
872 	const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
873 	bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
874 
875 	for (TileIndex tile_cur : tile_area) {
876 		CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
877 		if (ret.Failed()) return ret;
878 		cost.AddCost(ret);
879 
880 		if (slope_cb) {
881 			/* Do slope check if requested. */
882 			ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
883 			if (ret.Failed()) return ret;
884 		}
885 
886 		/* if station is set, then we have special handling to allow building on top of already existing stations.
887 		 * so station points to INVALID_STATION if we can build on any station.
888 		 * Or it points to a station if we're only allowed to build on exactly that station. */
889 		if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
890 			if (!IsRailStation(tile_cur)) {
891 				return ClearTile_Station(tile_cur, DC_AUTO); // get error message
892 			} else {
893 				StationID st = GetStationIndex(tile_cur);
894 				if (*station == INVALID_STATION) {
895 					*station = st;
896 				} else if (*station != st) {
897 					return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
898 				}
899 			}
900 		} else {
901 			/* Rail type is only valid when building a railway station; if station to
902 			 * build isn't a rail station it's INVALID_RAILTYPE. */
903 			if (rt != INVALID_RAILTYPE &&
904 					IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
905 					HasPowerOnRail(GetRailType(tile_cur), rt)) {
906 				/* Allow overbuilding if the tile:
907 				 *  - has rail, but no signals
908 				 *  - it has exactly one track
909 				 *  - the track is in line with the station
910 				 *  - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
911 				 */
912 				TrackBits tracks = GetTrackBits(tile_cur);
913 				Track track = RemoveFirstTrack(&tracks);
914 				Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
915 
916 				if (tracks == TRACK_BIT_NONE && track == expected_track) {
917 					/* Check for trains having a reservation for this tile. */
918 					if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
919 						Train *v = GetTrainForReservation(tile_cur, track);
920 						if (v != nullptr) {
921 							affected_vehicles.push_back(v);
922 						}
923 					}
924 					CommandCost ret = DoCommand(tile_cur, 0, track, flags, CMD_REMOVE_SINGLE_RAIL);
925 					if (ret.Failed()) return ret;
926 					cost.AddCost(ret);
927 					/* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
928 					continue;
929 				}
930 			}
931 			ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
932 			if (ret.Failed()) return ret;
933 			cost.AddCost(ret);
934 		}
935 	}
936 
937 	return cost;
938 }
939 
940 /**
941  * Checks if a road stop can be built at the given tile.
942  * @param tile_area Area to check.
943  * @param flags Operation to perform.
944  * @param invalid_dirs Prohibited directions (set of DiagDirections).
945  * @param is_drive_through True if trying to build a drive-through station.
946  * @param is_truck_stop True when building a truck stop, false otherwise.
947  * @param axis Axis of a drive-through road stop.
948  * @param station StationID to be queried and returned if available.
949  * @param rt Road type to build.
950  * @return The cost in case of success, or an error code if it failed.
951  */
CheckFlatLandRoadStop(TileArea tile_area,DoCommandFlag flags,uint invalid_dirs,bool is_drive_through,bool is_truck_stop,Axis axis,StationID * station,RoadType rt)952 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadType rt)
953 {
954 	CommandCost cost(EXPENSES_CONSTRUCTION);
955 	int allowed_z = -1;
956 
957 	for (TileIndex cur_tile : tile_area) {
958 		CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
959 		if (ret.Failed()) return ret;
960 		cost.AddCost(ret);
961 
962 		/* If station is set, then we have special handling to allow building on top of already existing stations.
963 		 * Station points to INVALID_STATION if we can build on any station.
964 		 * Or it points to a station if we're only allowed to build on exactly that station. */
965 		if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
966 			if (!IsRoadStop(cur_tile)) {
967 				return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
968 			} else {
969 				if (is_truck_stop != IsTruckStop(cur_tile) ||
970 						is_drive_through != IsDriveThroughStopTile(cur_tile)) {
971 					return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
972 				}
973 				/* Drive-through station in the wrong direction. */
974 				if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
975 					return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
976 				}
977 				StationID st = GetStationIndex(cur_tile);
978 				if (*station == INVALID_STATION) {
979 					*station = st;
980 				} else if (*station != st) {
981 					return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
982 				}
983 			}
984 		} else {
985 			bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
986 			/* Road bits in the wrong direction. */
987 			RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
988 			if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
989 				/* Someone was pedantic and *NEEDED* three fracking different error messages. */
990 				switch (CountBits(rb)) {
991 					case 1:
992 						return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
993 
994 					case 2:
995 						if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
996 						return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
997 
998 					default: // 3 or 4
999 						return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1000 				}
1001 			}
1002 
1003 			if (build_over_road) {
1004 				/* There is a road, check if we can build road+tram stop over it. */
1005 				RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1006 				if (road_rt != INVALID_ROADTYPE) {
1007 					Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1008 					if (road_owner == OWNER_TOWN) {
1009 						if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1010 					} else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1011 						CommandCost ret = CheckOwnership(road_owner);
1012 						if (ret.Failed()) return ret;
1013 					}
1014 					uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1015 
1016 					if (RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1017 
1018 					if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1019 						CommandCost ret = CheckOwnership(road_owner);
1020 						if (ret.Failed()) return ret;
1021 					}
1022 
1023 					cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1024 				} else if (RoadTypeIsRoad(rt)) {
1025 					cost.AddCost(RoadBuildCost(rt) * 2);
1026 				}
1027 
1028 				/* There is a tram, check if we can build road+tram stop over it. */
1029 				RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1030 				if (tram_rt != INVALID_ROADTYPE) {
1031 					Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1032 					if (Company::IsValidID(tram_owner) &&
1033 							(!_settings_game.construction.road_stop_on_competitor_road ||
1034 							/* Disallow breaking end-of-line of someone else
1035 							 * so trams can still reverse on this tile. */
1036 							HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1037 						CommandCost ret = CheckOwnership(tram_owner);
1038 						if (ret.Failed()) return ret;
1039 					}
1040 					uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1041 
1042 					if (RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1043 
1044 					cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1045 				} else if (RoadTypeIsTram(rt)) {
1046 					cost.AddCost(RoadBuildCost(rt) * 2);
1047 				}
1048 			} else {
1049 				ret = DoCommand(cur_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
1050 				if (ret.Failed()) return ret;
1051 				cost.AddCost(ret);
1052 				cost.AddCost(RoadBuildCost(rt) * 2);
1053 			}
1054 		}
1055 	}
1056 
1057 	return cost;
1058 }
1059 
1060 /**
1061  * Check whether we can expand the rail part of the given station.
1062  * @param st the station to expand
1063  * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1064  * @param axis the axis of the newly build rail
1065  * @return Succeeded or failed command.
1066  */
CanExpandRailStation(const BaseStation * st,TileArea & new_ta,Axis axis)1067 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
1068 {
1069 	TileArea cur_ta = st->train_station;
1070 
1071 	/* determine new size of train station region.. */
1072 	int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1073 	int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1074 	new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1075 	new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1076 	new_ta.tile = TileXY(x, y);
1077 
1078 	/* make sure the final size is not too big. */
1079 	if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1080 		return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1081 	}
1082 
1083 	return CommandCost();
1084 }
1085 
CreateSingle(byte * layout,int n)1086 static inline byte *CreateSingle(byte *layout, int n)
1087 {
1088 	int i = n;
1089 	do *layout++ = 0; while (--i);
1090 	layout[((n - 1) >> 1) - n] = 2;
1091 	return layout;
1092 }
1093 
CreateMulti(byte * layout,int n,byte b)1094 static inline byte *CreateMulti(byte *layout, int n, byte b)
1095 {
1096 	int i = n;
1097 	do *layout++ = b; while (--i);
1098 	if (n > 4) {
1099 		layout[0 - n] = 0;
1100 		layout[n - 1 - n] = 0;
1101 	}
1102 	return layout;
1103 }
1104 
1105 /**
1106  * Create the station layout for the given number of tracks and platform length.
1107  * @param layout    The layout to write to.
1108  * @param numtracks The number of tracks to write.
1109  * @param plat_len  The length of the platforms.
1110  * @param statspec  The specification of the station to (possibly) get the layout from.
1111  */
GetStationLayout(byte * layout,uint numtracks,uint plat_len,const StationSpec * statspec)1112 void GetStationLayout(byte *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1113 {
1114 	if (statspec != nullptr && statspec->layouts.size() >= plat_len &&
1115 			statspec->layouts[plat_len - 1].size() >= numtracks &&
1116 			!statspec->layouts[plat_len - 1][numtracks - 1].empty()) {
1117 		/* Custom layout defined, follow it. */
1118 		memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1].data(),
1119 			plat_len * numtracks);
1120 		return;
1121 	}
1122 
1123 	if (plat_len == 1) {
1124 		CreateSingle(layout, numtracks);
1125 	} else {
1126 		if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1127 		int n = numtracks >> 1;
1128 
1129 		while (--n >= 0) {
1130 			layout = CreateMulti(layout, plat_len, 4);
1131 			layout = CreateMulti(layout, plat_len, 6);
1132 		}
1133 	}
1134 }
1135 
1136 /**
1137  * Find a nearby station that joins this station.
1138  * @tparam T the class to find a station for
1139  * @tparam error_message the error message when building a station on top of others
1140  * @param existing_station an existing station we build over
1141  * @param station_to_join the station to join to
1142  * @param adjacent whether adjacent stations are allowed
1143  * @param ta the area of the newly build station
1144  * @param st 'return' pointer for the found station
1145  * @return command cost with the error or 'okay'
1146  */
1147 template <class T, StringID error_message>
FindJoiningBaseStation(StationID existing_station,StationID station_to_join,bool adjacent,TileArea ta,T ** st)1148 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1149 {
1150 	assert(*st == nullptr);
1151 	bool check_surrounding = true;
1152 
1153 	if (_settings_game.station.adjacent_stations) {
1154 		if (existing_station != INVALID_STATION) {
1155 			if (adjacent && existing_station != station_to_join) {
1156 				/* You can't build an adjacent station over the top of one that
1157 				 * already exists. */
1158 				return_cmd_error(error_message);
1159 			} else {
1160 				/* Extend the current station, and don't check whether it will
1161 				 * be near any other stations. */
1162 				*st = T::GetIfValid(existing_station);
1163 				check_surrounding = (*st == nullptr);
1164 			}
1165 		} else {
1166 			/* There's no station here. Don't check the tiles surrounding this
1167 			 * one if the company wanted to build an adjacent station. */
1168 			if (adjacent) check_surrounding = false;
1169 		}
1170 	}
1171 
1172 	if (check_surrounding) {
1173 		/* Make sure there is no more than one other station around us that is owned by us. */
1174 		CommandCost ret = GetStationAround(ta, existing_station, _current_company, st);
1175 		if (ret.Failed()) return ret;
1176 	}
1177 
1178 	/* Distant join */
1179 	if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1180 
1181 	return CommandCost();
1182 }
1183 
1184 /**
1185  * Find a nearby station that joins this station.
1186  * @param existing_station an existing station we build over
1187  * @param station_to_join the station to join to
1188  * @param adjacent whether adjacent stations are allowed
1189  * @param ta the area of the newly build station
1190  * @param st 'return' pointer for the found station
1191  * @return command cost with the error or 'okay'
1192  */
FindJoiningStation(StationID existing_station,StationID station_to_join,bool adjacent,TileArea ta,Station ** st)1193 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1194 {
1195 	return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1196 }
1197 
1198 /**
1199  * Find a nearby waypoint that joins this waypoint.
1200  * @param existing_waypoint an existing waypoint we build over
1201  * @param waypoint_to_join the waypoint to join to
1202  * @param adjacent whether adjacent waypoints are allowed
1203  * @param ta the area of the newly build waypoint
1204  * @param wp 'return' pointer for the found waypoint
1205  * @return command cost with the error or 'okay'
1206  */
FindJoiningWaypoint(StationID existing_waypoint,StationID waypoint_to_join,bool adjacent,TileArea ta,Waypoint ** wp)1207 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1208 {
1209 	return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1210 }
1211 
1212 /**
1213  * Clear platform reservation during station building/removing.
1214  * @param v vehicle which holds reservation
1215  */
FreeTrainReservation(Train * v)1216 static void FreeTrainReservation(Train *v)
1217 {
1218 	FreeTrainTrackReservation(v);
1219 	if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1220 	v = v->Last();
1221 	if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1222 }
1223 
1224 /**
1225  * Restore platform reservation during station building/removing.
1226  * @param v vehicle which held reservation
1227  */
RestoreTrainReservation(Train * v)1228 static void RestoreTrainReservation(Train *v)
1229 {
1230 	if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1231 	TryPathReserve(v, true, true);
1232 	v = v->Last();
1233 	if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1234 }
1235 
1236 /**
1237  * Build rail station
1238  * @param tile_org northern most position of station dragging/placement
1239  * @param flags operation to perform
1240  * @param p1 various bitstuffed elements
1241  * - p1 = (bit  0- 5) - railtype
1242  * - p1 = (bit  6)    - orientation (Axis)
1243  * - p1 = (bit  8-15) - number of tracks
1244  * - p1 = (bit 16-23) - platform length
1245  * - p1 = (bit 24)    - allow stations directly adjacent to other stations.
1246  * @param p2 various bitstuffed elements
1247  * - p2 = (bit  0- 7) - custom station class
1248  * - p2 = (bit  8-15) - custom station id
1249  * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1250  * @param text unused
1251  * @return the cost of this operation or an error
1252  */
CmdBuildRailStation(TileIndex tile_org,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1253 CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1254 {
1255 	/* Unpack parameters */
1256 	RailType rt    = Extract<RailType, 0, 6>(p1);
1257 	Axis axis      = Extract<Axis, 6, 1>(p1);
1258 	byte numtracks = GB(p1,  8, 8);
1259 	byte plat_len  = GB(p1, 16, 8);
1260 	bool adjacent  = HasBit(p1, 24);
1261 
1262 	StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
1263 	byte spec_index           = GB(p2, 8, 8);
1264 	StationID station_to_join = GB(p2, 16, 16);
1265 
1266 	/* Does the authority allow this? */
1267 	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1268 	if (ret.Failed()) return ret;
1269 
1270 	if (!ValParamRailtype(rt)) return CMD_ERROR;
1271 
1272 	/* Check if the given station class is valid */
1273 	if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1274 	if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1275 	if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1276 
1277 	int w_org, h_org;
1278 	if (axis == AXIS_X) {
1279 		w_org = plat_len;
1280 		h_org = numtracks;
1281 	} else {
1282 		h_org = plat_len;
1283 		w_org = numtracks;
1284 	}
1285 
1286 	bool reuse = (station_to_join != NEW_STATION);
1287 	if (!reuse) station_to_join = INVALID_STATION;
1288 	bool distant_join = (station_to_join != INVALID_STATION);
1289 
1290 	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1291 
1292 	if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1293 
1294 	/* these values are those that will be stored in train_tile and station_platforms */
1295 	TileArea new_location(tile_org, w_org, h_org);
1296 
1297 	/* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1298 	StationID est = INVALID_STATION;
1299 	std::vector<Train *> affected_vehicles;
1300 	/* Clear the land below the station. */
1301 	CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1302 	if (cost.Failed()) return cost;
1303 	/* Add construction expenses. */
1304 	cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1305 	cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1306 
1307 	Station *st = nullptr;
1308 	ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1309 	if (ret.Failed()) return ret;
1310 
1311 	ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1312 	if (ret.Failed()) return ret;
1313 
1314 	if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1315 		CommandCost ret = CanExpandRailStation(st, new_location, axis);
1316 		if (ret.Failed()) return ret;
1317 	}
1318 
1319 	/* Check if we can allocate a custom stationspec to this station */
1320 	const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1321 	int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1322 	if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1323 
1324 	if (statspec != nullptr) {
1325 		/* Perform NewStation checks */
1326 
1327 		/* Check if the station size is permitted */
1328 		if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) {
1329 			return CMD_ERROR;
1330 		}
1331 
1332 		/* Check if the station is buildable */
1333 		if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1334 			uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1335 			if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1336 		}
1337 	}
1338 
1339 	if (flags & DC_EXEC) {
1340 		TileIndexDiff tile_delta;
1341 		byte *layout_ptr;
1342 		byte numtracks_orig;
1343 		Track track;
1344 
1345 		st->train_station = new_location;
1346 		st->AddFacility(FACIL_TRAIN, new_location.tile);
1347 
1348 		st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1349 
1350 		if (statspec != nullptr) {
1351 			/* Include this station spec's animation trigger bitmask
1352 			 * in the station's cached copy. */
1353 			st->cached_anim_triggers |= statspec->animation.triggers;
1354 		}
1355 
1356 		tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1357 		track = AxisToTrack(axis);
1358 
1359 		layout_ptr = AllocaM(byte, numtracks * plat_len);
1360 		GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1361 
1362 		numtracks_orig = numtracks;
1363 
1364 		Company *c = Company::Get(st->owner);
1365 		TileIndex tile_track = tile_org;
1366 		do {
1367 			TileIndex tile = tile_track;
1368 			int w = plat_len;
1369 			do {
1370 				byte layout = *layout_ptr++;
1371 				if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1372 					/* Check for trains having a reservation for this tile. */
1373 					Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1374 					if (v != nullptr) {
1375 						affected_vehicles.push_back(v);
1376 						FreeTrainReservation(v);
1377 					}
1378 				}
1379 
1380 				/* Railtype can change when overbuilding. */
1381 				if (IsRailStationTile(tile)) {
1382 					if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1383 					c->infrastructure.station--;
1384 				}
1385 
1386 				/* Remove animation if overbuilding */
1387 				DeleteAnimatedTile(tile);
1388 				byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1389 				MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1390 				/* Free the spec if we overbuild something */
1391 				DeallocateSpecFromStation(st, old_specindex);
1392 
1393 				SetCustomStationSpecIndex(tile, specindex);
1394 				SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1395 				SetAnimationFrame(tile, 0);
1396 
1397 				if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1398 				c->infrastructure.station++;
1399 
1400 				if (statspec != nullptr) {
1401 					/* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1402 					uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1403 
1404 					/* As the station is not yet completely finished, the station does not yet exist. */
1405 					uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1406 					if (callback != CALLBACK_FAILED) {
1407 						if (callback < 8) {
1408 							SetStationGfx(tile, (callback & ~1) + axis);
1409 						} else {
1410 							ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1411 						}
1412 					}
1413 
1414 					/* Trigger station animation -- after building? */
1415 					TriggerStationAnimation(st, tile, SAT_BUILT);
1416 				}
1417 
1418 				tile += tile_delta;
1419 			} while (--w);
1420 			AddTrackToSignalBuffer(tile_track, track, _current_company);
1421 			YapfNotifyTrackLayoutChange(tile_track, track);
1422 			tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1423 		} while (--numtracks);
1424 
1425 		for (uint i = 0; i < affected_vehicles.size(); ++i) {
1426 			/* Restore reservations of trains. */
1427 			RestoreTrainReservation(affected_vehicles[i]);
1428 		}
1429 
1430 		/* Check whether we need to expand the reservation of trains already on the station. */
1431 		TileArea update_reservation_area;
1432 		if (axis == AXIS_X) {
1433 			update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1434 		} else {
1435 			update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1436 		}
1437 
1438 		for (TileIndex tile : update_reservation_area) {
1439 			/* Don't even try to make eye candy parts reserved. */
1440 			if (IsStationTileBlocked(tile)) continue;
1441 
1442 			DiagDirection dir = AxisToDiagDir(axis);
1443 			TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1444 			TileIndex platform_begin = tile;
1445 			TileIndex platform_end = tile;
1446 
1447 			/* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1448 			for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1449 				platform_begin = next_tile;
1450 			}
1451 			for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1452 				platform_end = next_tile;
1453 			}
1454 
1455 			/* If there is at least on reservation on the platform, we reserve the whole platform. */
1456 			bool reservation = false;
1457 			for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1458 				reservation = HasStationReservation(t);
1459 			}
1460 
1461 			if (reservation) {
1462 				SetRailStationPlatformReservation(platform_begin, dir, true);
1463 			}
1464 		}
1465 
1466 		st->MarkTilesDirty(false);
1467 		st->AfterStationTileSetChange(true, STATION_RAIL);
1468 	}
1469 
1470 	return cost;
1471 }
1472 
MakeStationAreaSmaller(BaseStation * st,TileArea ta,bool (* func)(BaseStation *,TileIndex))1473 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1474 {
1475 restart:
1476 
1477 	/* too small? */
1478 	if (ta.w != 0 && ta.h != 0) {
1479 		/* check the left side, x = constant, y changes */
1480 		for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1481 			/* the left side is unused? */
1482 			if (++i == ta.h) {
1483 				ta.tile += TileDiffXY(1, 0);
1484 				ta.w--;
1485 				goto restart;
1486 			}
1487 		}
1488 
1489 		/* check the right side, x = constant, y changes */
1490 		for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1491 			/* the right side is unused? */
1492 			if (++i == ta.h) {
1493 				ta.w--;
1494 				goto restart;
1495 			}
1496 		}
1497 
1498 		/* check the upper side, y = constant, x changes */
1499 		for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1500 			/* the left side is unused? */
1501 			if (++i == ta.w) {
1502 				ta.tile += TileDiffXY(0, 1);
1503 				ta.h--;
1504 				goto restart;
1505 			}
1506 		}
1507 
1508 		/* check the lower side, y = constant, x changes */
1509 		for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1510 			/* the left side is unused? */
1511 			if (++i == ta.w) {
1512 				ta.h--;
1513 				goto restart;
1514 			}
1515 		}
1516 	} else {
1517 		ta.Clear();
1518 	}
1519 
1520 	return ta;
1521 }
1522 
TileBelongsToRailStation(BaseStation * st,TileIndex tile)1523 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1524 {
1525 	return st->TileBelongsToRailStation(tile);
1526 }
1527 
MakeRailStationAreaSmaller(BaseStation * st)1528 static void MakeRailStationAreaSmaller(BaseStation *st)
1529 {
1530 	st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1531 }
1532 
TileBelongsToShipStation(BaseStation * st,TileIndex tile)1533 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1534 {
1535 	return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1536 }
1537 
MakeShipStationAreaSmaller(Station * st)1538 static void MakeShipStationAreaSmaller(Station *st)
1539 {
1540 	st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1541 	UpdateStationDockingTiles(st);
1542 }
1543 
1544 /**
1545  * Remove a number of tiles from any rail station within the area.
1546  * @param ta the area to clear station tile from.
1547  * @param affected_stations the stations affected.
1548  * @param flags the command flags.
1549  * @param removal_cost the cost for removing the tile, including the rail.
1550  * @param keep_rail whether to keep the rail of the station.
1551  * @tparam T the type of station to remove.
1552  * @return the number of cleared tiles or an error.
1553  */
1554 template <class T>
RemoveFromRailBaseStation(TileArea ta,std::vector<T * > & affected_stations,DoCommandFlag flags,Money removal_cost,bool keep_rail)1555 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1556 {
1557 	/* Count of the number of tiles removed */
1558 	int quantity = 0;
1559 	CommandCost total_cost(EXPENSES_CONSTRUCTION);
1560 	/* Accumulator for the errors seen during clearing. If no errors happen,
1561 	 * and the quantity is 0 there is no station. Otherwise it will be one
1562 	 * of the other error that got accumulated. */
1563 	CommandCost error;
1564 
1565 	/* Do the action for every tile into the area */
1566 	for (TileIndex tile : ta) {
1567 		/* Make sure the specified tile is a rail station */
1568 		if (!HasStationTileRail(tile)) continue;
1569 
1570 		/* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1571 		CommandCost ret = EnsureNoVehicleOnGround(tile);
1572 		error.AddCost(ret);
1573 		if (ret.Failed()) continue;
1574 
1575 		/* Check ownership of station */
1576 		T *st = T::GetByTile(tile);
1577 		if (st == nullptr) continue;
1578 
1579 		if (_current_company != OWNER_WATER) {
1580 			CommandCost ret = CheckOwnership(st->owner);
1581 			error.AddCost(ret);
1582 			if (ret.Failed()) continue;
1583 		}
1584 
1585 		/* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1586 		quantity++;
1587 
1588 		if (keep_rail || IsStationTileBlocked(tile)) {
1589 			/* Don't refund the 'steel' of the track when we keep the
1590 			 *  rail, or when the tile didn't have any rail at all. */
1591 			total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1592 		}
1593 
1594 		if (flags & DC_EXEC) {
1595 			/* read variables before the station tile is removed */
1596 			uint specindex = GetCustomStationSpecIndex(tile);
1597 			Track track = GetRailStationTrack(tile);
1598 			Owner owner = GetTileOwner(tile);
1599 			RailType rt = GetRailType(tile);
1600 			Train *v = nullptr;
1601 
1602 			if (HasStationReservation(tile)) {
1603 				v = GetTrainForReservation(tile, track);
1604 				if (v != nullptr) FreeTrainReservation(v);
1605 			}
1606 
1607 			bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1608 			if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1609 
1610 			DoClearSquare(tile);
1611 			DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1612 			if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1613 			Company::Get(owner)->infrastructure.station--;
1614 			DirtyCompanyInfrastructureWindows(owner);
1615 
1616 			st->rect.AfterRemoveTile(st, tile);
1617 			AddTrackToSignalBuffer(tile, track, owner);
1618 			YapfNotifyTrackLayoutChange(tile, track);
1619 
1620 			DeallocateSpecFromStation(st, specindex);
1621 
1622 			include(affected_stations, st);
1623 
1624 			if (v != nullptr) RestoreTrainReservation(v);
1625 		}
1626 	}
1627 
1628 	if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1629 
1630 	for (T *st : affected_stations) {
1631 
1632 		/* now we need to make the "spanned" area of the railway station smaller
1633 		 * if we deleted something at the edges.
1634 		 * we also need to adjust train_tile. */
1635 		MakeRailStationAreaSmaller(st);
1636 		UpdateStationSignCoord(st);
1637 
1638 		/* if we deleted the whole station, delete the train facility. */
1639 		if (st->train_station.tile == INVALID_TILE) {
1640 			st->facilities &= ~FACIL_TRAIN;
1641 			SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1642 			st->UpdateVirtCoord();
1643 			DeleteStationIfEmpty(st);
1644 		}
1645 	}
1646 
1647 	total_cost.AddCost(quantity * removal_cost);
1648 	return total_cost;
1649 }
1650 
1651 /**
1652  * Remove a single tile from a rail station.
1653  * This allows for custom-built station with holes and weird layouts
1654  * @param start tile of station piece to remove
1655  * @param flags operation to perform
1656  * @param p1 start_tile
1657  * @param p2 various bitstuffed elements
1658  * - p2 = bit 0 - if set keep the rail
1659  * @param text unused
1660  * @return the cost of this operation or an error
1661  */
CmdRemoveFromRailStation(TileIndex start,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1662 CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1663 {
1664 	TileIndex end = p1 == 0 ? start : p1;
1665 	if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1666 
1667 	TileArea ta(start, end);
1668 	std::vector<Station *> affected_stations;
1669 
1670 	CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], HasBit(p2, 0));
1671 	if (ret.Failed()) return ret;
1672 
1673 	/* Do all station specific functions here. */
1674 	for (Station *st : affected_stations) {
1675 
1676 		if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1677 		st->MarkTilesDirty(false);
1678 		st->RecomputeCatchment();
1679 	}
1680 
1681 	/* Now apply the rail cost to the number that we deleted */
1682 	return ret;
1683 }
1684 
1685 /**
1686  * Remove a single tile from a waypoint.
1687  * This allows for custom-built waypoint with holes and weird layouts
1688  * @param start tile of waypoint piece to remove
1689  * @param flags operation to perform
1690  * @param p1 start_tile
1691  * @param p2 various bitstuffed elements
1692  * - p2 = bit 0 - if set keep the rail
1693  * @param text unused
1694  * @return the cost of this operation or an error
1695  */
CmdRemoveFromRailWaypoint(TileIndex start,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1696 CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1697 {
1698 	TileIndex end = p1 == 0 ? start : p1;
1699 	if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1700 
1701 	TileArea ta(start, end);
1702 	std::vector<Waypoint *> affected_stations;
1703 
1704 	return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], HasBit(p2, 0));
1705 }
1706 
1707 
1708 /**
1709  * Remove a rail station/waypoint
1710  * @param st The station/waypoint to remove the rail part from
1711  * @param flags operation to perform
1712  * @param removal_cost the cost for removing a tile
1713  * @tparam T the type of station to remove
1714  * @return cost or failure of operation
1715  */
1716 template <class T>
RemoveRailStation(T * st,DoCommandFlag flags,Money removal_cost)1717 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1718 {
1719 	/* Current company owns the station? */
1720 	if (_current_company != OWNER_WATER) {
1721 		CommandCost ret = CheckOwnership(st->owner);
1722 		if (ret.Failed()) return ret;
1723 	}
1724 
1725 	/* determine width and height of platforms */
1726 	TileArea ta = st->train_station;
1727 
1728 	assert(ta.w != 0 && ta.h != 0);
1729 
1730 	CommandCost cost(EXPENSES_CONSTRUCTION);
1731 	/* clear all areas of the station */
1732 	for (TileIndex tile : ta) {
1733 		/* only remove tiles that are actually train station tiles */
1734 		if (st->TileBelongsToRailStation(tile)) {
1735 			std::vector<T*> affected_stations; // dummy
1736 			CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1737 			if (ret.Failed()) return ret;
1738 			cost.AddCost(ret);
1739 		}
1740 	}
1741 
1742 	return cost;
1743 }
1744 
1745 /**
1746  * Remove a rail station
1747  * @param tile Tile of the station.
1748  * @param flags operation to perform
1749  * @return cost or failure of operation
1750  */
RemoveRailStation(TileIndex tile,DoCommandFlag flags)1751 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1752 {
1753 	/* if there is flooding, remove platforms tile by tile */
1754 	if (_current_company == OWNER_WATER) {
1755 		return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_STATION);
1756 	}
1757 
1758 	Station *st = Station::GetByTile(tile);
1759 	CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1760 
1761 	if (flags & DC_EXEC) st->RecomputeCatchment();
1762 
1763 	return cost;
1764 }
1765 
1766 /**
1767  * Remove a rail waypoint
1768  * @param tile Tile of the waypoint.
1769  * @param flags operation to perform
1770  * @return cost or failure of operation
1771  */
RemoveRailWaypoint(TileIndex tile,DoCommandFlag flags)1772 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1773 {
1774 	/* if there is flooding, remove waypoints tile by tile */
1775 	if (_current_company == OWNER_WATER) {
1776 		return DoCommand(tile, 0, 0, DC_EXEC, CMD_REMOVE_FROM_RAIL_WAYPOINT);
1777 	}
1778 
1779 	return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1780 }
1781 
1782 
1783 /**
1784  * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1785  * @param st The Station to do the whole procedure for
1786  * @return a pointer to where to link a new RoadStop*
1787  */
FindRoadStopSpot(bool truck_station,Station * st)1788 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1789 {
1790 	RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1791 
1792 	if (*primary_stop == nullptr) {
1793 		/* we have no roadstop of the type yet, so write a "primary stop" */
1794 		return primary_stop;
1795 	} else {
1796 		/* there are stops already, so append to the end of the list */
1797 		RoadStop *stop = *primary_stop;
1798 		while (stop->next != nullptr) stop = stop->next;
1799 		return &stop->next;
1800 	}
1801 }
1802 
1803 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1804 
1805 /**
1806  * Find a nearby station that joins this road stop.
1807  * @param existing_stop an existing road stop we build over
1808  * @param station_to_join the station to join to
1809  * @param adjacent whether adjacent stations are allowed
1810  * @param ta the area of the newly build station
1811  * @param st 'return' pointer for the found station
1812  * @return command cost with the error or 'okay'
1813  */
FindJoiningRoadStop(StationID existing_stop,StationID station_to_join,bool adjacent,TileArea ta,Station ** st)1814 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1815 {
1816 	return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1817 }
1818 
1819 /**
1820  * Build a bus or truck stop.
1821  * @param tile Northernmost tile of the stop.
1822  * @param flags Operation to perform.
1823  * @param p1 bit 0..7: Width of the road stop.
1824  *           bit 8..15: Length of the road stop.
1825  * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1826  *           bit 1: 0 For normal stops, 1 for drive-through.
1827  *           bit 2: Allow stations directly adjacent to other stations.
1828  *           bit 3..4: Entrance direction (#DiagDirection) for normal stops.
1829  *           bit 3: #Axis of the road for drive-through stops.
1830  *           bit 5..10: The roadtype.
1831  *           bit 16..31: Station ID to join (NEW_STATION if build new one).
1832  * @param text Unused.
1833  * @return The cost of this operation or an error.
1834  */
CmdBuildRoadStop(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)1835 CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
1836 {
1837 	bool type = HasBit(p2, 0);
1838 	bool is_drive_through = HasBit(p2, 1);
1839 	RoadType rt = Extract<RoadType, 5, 6>(p2);
1840 	if (!ValParamRoadType(rt)) return CMD_ERROR;
1841 	StationID station_to_join = GB(p2, 16, 16);
1842 	bool reuse = (station_to_join != NEW_STATION);
1843 	if (!reuse) station_to_join = INVALID_STATION;
1844 	bool distant_join = (station_to_join != INVALID_STATION);
1845 
1846 	uint8 width = (uint8)GB(p1, 0, 8);
1847 	uint8 length = (uint8)GB(p1, 8, 8);
1848 
1849 	/* Check if the requested road stop is too big */
1850 	if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1851 	/* Check for incorrect width / length. */
1852 	if (width == 0 || length == 0) return CMD_ERROR;
1853 	/* Check if the first tile and the last tile are valid */
1854 	if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1855 
1856 	TileArea roadstop_area(tile, width, length);
1857 
1858 	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1859 
1860 	/* Trams only have drive through stops */
1861 	if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
1862 
1863 	DiagDirection ddir;
1864 	Axis axis;
1865 	if (is_drive_through) {
1866 		/* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1867 		axis = Extract<Axis, 3, 1>(p2);
1868 		ddir = AxisToDiagDir(axis);
1869 	} else {
1870 		/* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1871 		ddir = Extract<DiagDirection, 3, 2>(p2);
1872 		axis = DiagDirToAxis(ddir);
1873 	}
1874 
1875 	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1876 	if (ret.Failed()) return ret;
1877 
1878 	/* Total road stop cost. */
1879 	CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[type ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1880 	StationID est = INVALID_STATION;
1881 	ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, type, axis, &est, rt);
1882 	if (ret.Failed()) return ret;
1883 	cost.AddCost(ret);
1884 
1885 	Station *st = nullptr;
1886 	ret = FindJoiningRoadStop(est, station_to_join, HasBit(p2, 2), roadstop_area, &st);
1887 	if (ret.Failed()) return ret;
1888 
1889 	/* Check if this number of road stops can be allocated. */
1890 	if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(type ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1891 
1892 	ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1893 	if (ret.Failed()) return ret;
1894 
1895 	if (flags & DC_EXEC) {
1896 		/* Check every tile in the area. */
1897 		for (TileIndex cur_tile : roadstop_area) {
1898 			/* Get existing road types and owners before any tile clearing */
1899 			RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
1900 			RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
1901 			Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
1902 			Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
1903 
1904 			if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
1905 				RemoveRoadStop(cur_tile, flags);
1906 			}
1907 
1908 			RoadStop *road_stop = new RoadStop(cur_tile);
1909 			/* Insert into linked list of RoadStops. */
1910 			RoadStop **currstop = FindRoadStopSpot(type, st);
1911 			*currstop = road_stop;
1912 
1913 			if (type) {
1914 				st->truck_station.Add(cur_tile);
1915 			} else {
1916 				st->bus_station.Add(cur_tile);
1917 			}
1918 
1919 			/* Initialize an empty station. */
1920 			st->AddFacility((type) ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1921 
1922 			st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1923 
1924 			RoadStopType rs_type = type ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1925 			if (is_drive_through) {
1926 				/* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
1927 				 * bits first. */
1928 				if (IsNormalRoadTile(cur_tile)) {
1929 					UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
1930 					UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
1931 				}
1932 
1933 				if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
1934 				if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
1935 
1936 				UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
1937 				UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
1938 
1939 				MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, road_rt, tram_rt, axis);
1940 				road_stop->MakeDriveThrough();
1941 			} else {
1942 				if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
1943 				if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
1944 				/* Non-drive-through stop never overbuild and always count as two road bits. */
1945 				Company::Get(st->owner)->infrastructure.road[rt] += ROAD_STOP_TRACKBIT_FACTOR;
1946 				MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
1947 			}
1948 			Company::Get(st->owner)->infrastructure.station++;
1949 
1950 			MarkTileDirtyByTile(cur_tile);
1951 		}
1952 	}
1953 
1954 	if (st != nullptr) {
1955 		st->AfterStationTileSetChange(true, type ? STATION_TRUCK: STATION_BUS);
1956 	}
1957 	return cost;
1958 }
1959 
1960 
ClearRoadStopStatusEnum(Vehicle * v,void *)1961 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
1962 {
1963 	if (v->type == VEH_ROAD) {
1964 		/* Okay... we are a road vehicle on a drive through road stop.
1965 		 * But that road stop has just been removed, so we need to make
1966 		 * sure we are in a valid state... however, vehicles can also
1967 		 * turn on road stop tiles, so only clear the 'road stop' state
1968 		 * bits and only when the state was 'in road stop', otherwise
1969 		 * we'll end up clearing the turn around bits. */
1970 		RoadVehicle *rv = RoadVehicle::From(v);
1971 		if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1972 	}
1973 
1974 	return nullptr;
1975 }
1976 
1977 
1978 /**
1979  * Remove a bus station/truck stop
1980  * @param tile TileIndex been queried
1981  * @param flags operation to perform
1982  * @return cost or failure of operation
1983  */
RemoveRoadStop(TileIndex tile,DoCommandFlag flags)1984 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1985 {
1986 	Station *st = Station::GetByTile(tile);
1987 
1988 	if (_current_company != OWNER_WATER) {
1989 		CommandCost ret = CheckOwnership(st->owner);
1990 		if (ret.Failed()) return ret;
1991 	}
1992 
1993 	bool is_truck = IsTruckStop(tile);
1994 
1995 	RoadStop **primary_stop;
1996 	RoadStop *cur_stop;
1997 	if (is_truck) { // truck stop
1998 		primary_stop = &st->truck_stops;
1999 		cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2000 	} else {
2001 		primary_stop = &st->bus_stops;
2002 		cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2003 	}
2004 
2005 	assert(cur_stop != nullptr);
2006 
2007 	/* don't do the check for drive-through road stops when company bankrupts */
2008 	if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2009 		/* remove the 'going through road stop' status from all vehicles on that tile */
2010 		if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2011 	} else {
2012 		CommandCost ret = EnsureNoVehicleOnGround(tile);
2013 		if (ret.Failed()) return ret;
2014 	}
2015 
2016 	if (flags & DC_EXEC) {
2017 		if (*primary_stop == cur_stop) {
2018 			/* removed the first stop in the list */
2019 			*primary_stop = cur_stop->next;
2020 			/* removed the only stop? */
2021 			if (*primary_stop == nullptr) {
2022 				st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2023 			}
2024 		} else {
2025 			/* tell the predecessor in the list to skip this stop */
2026 			RoadStop *pred = *primary_stop;
2027 			while (pred->next != cur_stop) pred = pred->next;
2028 			pred->next = cur_stop->next;
2029 		}
2030 
2031 		/* Update company infrastructure counts. */
2032 		for (RoadTramType rtt : _roadtramtypes) {
2033 			RoadType rt = GetRoadType(tile, rtt);
2034 			UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2035 		}
2036 
2037 		Company::Get(st->owner)->infrastructure.station--;
2038 		DirtyCompanyInfrastructureWindows(st->owner);
2039 
2040 		if (IsDriveThroughStopTile(tile)) {
2041 			/* Clears the tile for us */
2042 			cur_stop->ClearDriveThrough();
2043 		} else {
2044 			DoClearSquare(tile);
2045 		}
2046 
2047 		delete cur_stop;
2048 
2049 		/* Make sure no vehicle is going to the old roadstop */
2050 		for (RoadVehicle *v : RoadVehicle::Iterate()) {
2051 			if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
2052 					v->dest_tile == tile) {
2053 				v->SetDestTile(v->GetOrderStationLocation(st->index));
2054 			}
2055 		}
2056 
2057 		st->rect.AfterRemoveTile(st, tile);
2058 
2059 		st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2060 
2061 		/* Update the tile area of the truck/bus stop */
2062 		if (is_truck) {
2063 			st->truck_station.Clear();
2064 			for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2065 		} else {
2066 			st->bus_station.Clear();
2067 			for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2068 		}
2069 	}
2070 
2071 	return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
2072 }
2073 
2074 /**
2075  * Remove bus or truck stops.
2076  * @param tile Northernmost tile of the removal area.
2077  * @param flags Operation to perform.
2078  * @param p1 bit 0..7: Width of the removal area.
2079  *           bit 8..15: Height of the removal area.
2080  * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2081  * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2082  * @param text Unused.
2083  * @return The cost of this operation or an error.
2084  */
CmdRemoveRoadStop(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2085 CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2086 {
2087 	uint8 width = (uint8)GB(p1, 0, 8);
2088 	uint8 height = (uint8)GB(p1, 8, 8);
2089 	bool keep_drive_through_roads = !HasBit(p2, 1);
2090 
2091 	/* Check for incorrect width / height. */
2092 	if (width == 0 || height == 0) return CMD_ERROR;
2093 	/* Check if the first tile and the last tile are valid */
2094 	if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2095 	/* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2096 	if (!keep_drive_through_roads && (flags & DC_BANKRUPT)) return CMD_ERROR;
2097 
2098 	TileArea roadstop_area(tile, width, height);
2099 
2100 	CommandCost cost(EXPENSES_CONSTRUCTION);
2101 	CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2102 	bool had_success = false;
2103 
2104 	for (TileIndex cur_tile : roadstop_area) {
2105 		/* Make sure the specified tile is a road stop of the correct type */
2106 		if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || (uint32)GetRoadStopType(cur_tile) != GB(p2, 0, 1)) continue;
2107 
2108 		/* Save information on to-be-restored roads before the stop is removed. */
2109 		RoadBits road_bits = ROAD_NONE;
2110 		RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2111 		Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2112 		if (IsDriveThroughStopTile(cur_tile)) {
2113 			for (RoadTramType rtt : _roadtramtypes) {
2114 				road_type[rtt] = GetRoadType(cur_tile, rtt);
2115 				if (road_type[rtt] == INVALID_ROADTYPE) continue;
2116 				road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2117 				/* If we don't want to preserve our roads then restore only roads of others. */
2118 				if (!keep_drive_through_roads && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2119 			}
2120 			road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2121 		}
2122 
2123 		CommandCost ret = RemoveRoadStop(cur_tile, flags);
2124 		if (ret.Failed()) {
2125 			last_error = ret;
2126 			continue;
2127 		}
2128 		cost.AddCost(ret);
2129 		had_success = true;
2130 
2131 		/* Restore roads. */
2132 		if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2133 			MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2134 					road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2135 
2136 			/* Update company infrastructure counts. */
2137 			int count = CountBits(road_bits);
2138 			UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2139 			UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2140 		}
2141 	}
2142 
2143 	return had_success ? cost : last_error;
2144 }
2145 
2146 /**
2147  * Get a possible noise reduction factor based on distance from town center.
2148  * The further you get, the less noise you generate.
2149  * So all those folks at city council can now happily slee...  work in their offices
2150  * @param as airport information
2151  * @param distance minimum distance between town and airport
2152  * @return the noise that will be generated, according to distance
2153  */
GetAirportNoiseLevelForDistance(const AirportSpec * as,uint distance)2154 uint8 GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2155 {
2156 	/* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2157 	 * So no need to go any further*/
2158 	if (as->noise_level < 2) return as->noise_level;
2159 
2160 	/* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2161 	 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2162 	 * Basically, it says that the less tolerant a town is, the bigger the distance before
2163 	 * an actual decrease can be granted */
2164 	uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2165 
2166 	/* now, we want to have the distance segmented using the distance judged bareable by town
2167 	 * This will give us the coefficient of reduction the distance provides. */
2168 	uint noise_reduction = distance / town_tolerance_distance;
2169 
2170 	/* If the noise reduction equals the airport noise itself, don't give it for free.
2171 	 * Otherwise, simply reduce the airport's level. */
2172 	return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2173 }
2174 
2175 /**
2176  * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2177  * If two towns have the same distance, town with lower index is returned.
2178  * @param as airport's description
2179  * @param it An iterator over all airport tiles
2180  * @param[out] mindist Minimum distance to town
2181  * @return nearest town to airport
2182  */
AirportGetNearestTown(const AirportSpec * as,const TileIterator & it,uint & mindist)2183 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it, uint &mindist)
2184 {
2185 	assert(Town::GetNumItems() > 0);
2186 
2187 	Town *nearest = nullptr;
2188 
2189 	uint perimeter_min_x = TileX(it);
2190 	uint perimeter_min_y = TileY(it);
2191 	uint perimeter_max_x = perimeter_min_x + as->size_x - 1;
2192 	uint perimeter_max_y = perimeter_min_y + as->size_y - 1;
2193 
2194 	mindist = UINT_MAX - 1; // prevent overflow
2195 
2196 	std::unique_ptr<TileIterator> copy(it.Clone());
2197 	for (TileIndex cur_tile = *copy; cur_tile != INVALID_TILE; cur_tile = ++*copy) {
2198 		if (TileX(cur_tile) == perimeter_min_x || TileX(cur_tile) == perimeter_max_x || TileY(cur_tile) == perimeter_min_y || TileY(cur_tile) == perimeter_max_y) {
2199 			Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2200 			if (t == nullptr) continue;
2201 
2202 			uint dist = DistanceManhattan(t->xy, cur_tile);
2203 			if (dist == mindist && t->index < nearest->index) nearest = t;
2204 			if (dist < mindist) {
2205 				nearest = t;
2206 				mindist = dist;
2207 			}
2208 		}
2209 	}
2210 
2211 	return nearest;
2212 }
2213 
2214 
2215 /** Recalculate the noise generated by the airports of each town */
UpdateAirportsNoise()2216 void UpdateAirportsNoise()
2217 {
2218 	for (Town *t : Town::Iterate()) t->noise_reached = 0;
2219 
2220 	for (const Station *st : Station::Iterate()) {
2221 		if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2222 			const AirportSpec *as = st->airport.GetSpec();
2223 			AirportTileIterator it(st);
2224 			uint dist;
2225 			Town *nearest = AirportGetNearestTown(as, it, dist);
2226 			nearest->noise_reached += GetAirportNoiseLevelForDistance(as, dist);
2227 		}
2228 	}
2229 }
2230 
2231 /**
2232  * Place an Airport.
2233  * @param tile tile where airport will be built
2234  * @param flags operation to perform
2235  * @param p1
2236  * - p1 = (bit  0- 7) - airport type, @see airport.h
2237  * - p1 = (bit  8-15) - airport layout
2238  * @param p2 various bitstuffed elements
2239  * - p2 = (bit     0) - allow airports directly adjacent to other airports.
2240  * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2241  * @param text unused
2242  * @return the cost of this operation or an error
2243  */
CmdBuildAirport(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2244 CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2245 {
2246 	StationID station_to_join = GB(p2, 16, 16);
2247 	bool reuse = (station_to_join != NEW_STATION);
2248 	if (!reuse) station_to_join = INVALID_STATION;
2249 	bool distant_join = (station_to_join != INVALID_STATION);
2250 	byte airport_type = GB(p1, 0, 8);
2251 	byte layout = GB(p1, 8, 8);
2252 
2253 	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2254 
2255 	if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2256 
2257 	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2258 	if (ret.Failed()) return ret;
2259 
2260 	/* Check if a valid, buildable airport was chosen for construction */
2261 	const AirportSpec *as = AirportSpec::Get(airport_type);
2262 	if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2263 	if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2264 
2265 	Direction rotation = as->rotation[layout];
2266 	int w = as->size_x;
2267 	int h = as->size_y;
2268 	if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2269 	TileArea airport_area = TileArea(tile, w, h);
2270 
2271 	if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2272 		return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2273 	}
2274 
2275 	AirportTileTableIterator iter(as->table[layout], tile);
2276 	CommandCost cost = CheckFlatLandAirport(iter, flags);
2277 	if (cost.Failed()) return cost;
2278 
2279 	/* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2280 	uint dist;
2281 	Town *nearest = AirportGetNearestTown(as, iter, dist);
2282 	uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2283 
2284 	/* Check if local auth would allow a new airport */
2285 	StringID authority_refuse_message = STR_NULL;
2286 	Town *authority_refuse_town = nullptr;
2287 
2288 	if (_settings_game.economy.station_noise_level) {
2289 		/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2290 		if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2291 			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2292 			authority_refuse_town = nearest;
2293 		}
2294 	} else {
2295 		Town *t = ClosestTownFromTile(tile, UINT_MAX);
2296 		uint num = 0;
2297 		for (const Station *st : Station::Iterate()) {
2298 			if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2299 		}
2300 		if (num >= 2) {
2301 			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2302 			authority_refuse_town = t;
2303 		}
2304 	}
2305 
2306 	if (authority_refuse_message != STR_NULL) {
2307 		SetDParam(0, authority_refuse_town->index);
2308 		return_cmd_error(authority_refuse_message);
2309 	}
2310 
2311 	Station *st = nullptr;
2312 	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), airport_area, &st);
2313 	if (ret.Failed()) return ret;
2314 
2315 	/* Distant join */
2316 	if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2317 
2318 	ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2319 	if (ret.Failed()) return ret;
2320 
2321 	if (st != nullptr && st->airport.tile != INVALID_TILE) {
2322 		return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2323 	}
2324 
2325 	for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2326 		cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2327 	}
2328 
2329 	if (flags & DC_EXEC) {
2330 		/* Always add the noise, so there will be no need to recalculate when option toggles */
2331 		nearest->noise_reached += newnoise_level;
2332 
2333 		st->AddFacility(FACIL_AIRPORT, tile);
2334 		st->airport.type = airport_type;
2335 		st->airport.layout = layout;
2336 		st->airport.flags = 0;
2337 		st->airport.rotation = rotation;
2338 
2339 		st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2340 
2341 		for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2342 			MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2343 			SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2344 			st->airport.Add(iter);
2345 
2346 			if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2347 		}
2348 
2349 		/* Only call the animation trigger after all tiles have been built */
2350 		for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2351 			AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2352 		}
2353 
2354 		UpdateAirplanesOnNewStation(st);
2355 
2356 		Company::Get(st->owner)->infrastructure.airport++;
2357 
2358 		st->AfterStationTileSetChange(true, STATION_AIRPORT);
2359 		InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2360 
2361 		if (_settings_game.economy.station_noise_level) {
2362 			SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2363 		}
2364 	}
2365 
2366 	return cost;
2367 }
2368 
2369 /**
2370  * Remove an airport
2371  * @param tile TileIndex been queried
2372  * @param flags operation to perform
2373  * @return cost or failure of operation
2374  */
RemoveAirport(TileIndex tile,DoCommandFlag flags)2375 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2376 {
2377 	Station *st = Station::GetByTile(tile);
2378 
2379 	if (_current_company != OWNER_WATER) {
2380 		CommandCost ret = CheckOwnership(st->owner);
2381 		if (ret.Failed()) return ret;
2382 	}
2383 
2384 	tile = st->airport.tile;
2385 
2386 	CommandCost cost(EXPENSES_CONSTRUCTION);
2387 
2388 	for (const Aircraft *a : Aircraft::Iterate()) {
2389 		if (!a->IsNormalAircraft()) continue;
2390 		if (a->targetairport == st->index && a->state != FLYING) {
2391 			return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2392 		}
2393 	}
2394 
2395 	if (flags & DC_EXEC) {
2396 		for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2397 			TileIndex tile_cur = st->airport.GetHangarTile(i);
2398 			OrderBackup::Reset(tile_cur, false);
2399 			CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2400 		}
2401 
2402 		const AirportSpec *as = st->airport.GetSpec();
2403 		/* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2404 		 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2405 		 * need of recalculation */
2406 		AirportTileIterator it(st);
2407 		uint dist;
2408 		Town *nearest = AirportGetNearestTown(as, it, dist);
2409 		nearest->noise_reached -= GetAirportNoiseLevelForDistance(as, dist);
2410 
2411 		if (_settings_game.economy.station_noise_level) {
2412 			SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2413 		}
2414 	}
2415 
2416 	for (TileIndex tile_cur : st->airport) {
2417 		if (!st->TileBelongsToAirport(tile_cur)) continue;
2418 
2419 		CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2420 		if (ret.Failed()) return ret;
2421 
2422 		cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2423 
2424 		if (flags & DC_EXEC) {
2425 			DeleteAnimatedTile(tile_cur);
2426 			DoClearSquare(tile_cur);
2427 			DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2428 		}
2429 	}
2430 
2431 	if (flags & DC_EXEC) {
2432 		/* Clear the persistent storage. */
2433 		delete st->airport.psa;
2434 
2435 		st->rect.AfterRemoveRect(st, st->airport);
2436 
2437 		st->airport.Clear();
2438 		st->facilities &= ~FACIL_AIRPORT;
2439 
2440 		InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2441 
2442 		Company::Get(st->owner)->infrastructure.airport--;
2443 
2444 		st->AfterStationTileSetChange(false, STATION_AIRPORT);
2445 
2446 		DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2447 	}
2448 
2449 	return cost;
2450 }
2451 
2452 /**
2453  * Open/close an airport to incoming aircraft.
2454  * @param tile Unused.
2455  * @param flags Operation to perform.
2456  * @param p1 Station ID of the airport.
2457  * @param p2 Unused.
2458  * @param text unused
2459  * @return the cost of this operation or an error
2460  */
CmdOpenCloseAirport(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2461 CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2462 {
2463 	if (!Station::IsValidID(p1)) return CMD_ERROR;
2464 	Station *st = Station::Get(p1);
2465 
2466 	if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2467 
2468 	CommandCost ret = CheckOwnership(st->owner);
2469 	if (ret.Failed()) return ret;
2470 
2471 	if (flags & DC_EXEC) {
2472 		st->airport.flags ^= AIRPORT_CLOSED_block;
2473 		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2474 	}
2475 	return CommandCost();
2476 }
2477 
2478 /**
2479  * Tests whether the company's vehicles have this station in orders
2480  * @param station station ID
2481  * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2482  * @param company company ID
2483  */
HasStationInUse(StationID station,bool include_company,CompanyID company)2484 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2485 {
2486 	for (const Vehicle *v : Vehicle::Iterate()) {
2487 		if ((v->owner == company) == include_company) {
2488 			for (const Order *order : v->Orders()) {
2489 				if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2490 					return true;
2491 				}
2492 			}
2493 		}
2494 	}
2495 	return false;
2496 }
2497 
2498 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2499 	{-1,  0},
2500 	{ 0,  0},
2501 	{ 0,  0},
2502 	{ 0, -1}
2503 };
2504 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2505 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2506 
2507 /**
2508  * Build a dock/haven.
2509  * @param tile tile where dock will be built
2510  * @param flags operation to perform
2511  * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2512  * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2513  * @param text unused
2514  * @return the cost of this operation or an error
2515  */
CmdBuildDock(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)2516 CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
2517 {
2518 	StationID station_to_join = GB(p2, 16, 16);
2519 	bool reuse = (station_to_join != NEW_STATION);
2520 	if (!reuse) station_to_join = INVALID_STATION;
2521 	bool distant_join = (station_to_join != INVALID_STATION);
2522 
2523 	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2524 
2525 	DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2526 	if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2527 	direction = ReverseDiagDir(direction);
2528 
2529 	/* Docks cannot be placed on rapids */
2530 	if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2531 
2532 	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2533 	if (ret.Failed()) return ret;
2534 
2535 	if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2536 
2537 	CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2538 	ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2539 	if (ret.Failed()) return ret;
2540 	cost.AddCost(ret);
2541 
2542 	TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2543 
2544 	if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2545 		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2546 	}
2547 
2548 	if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2549 
2550 	/* Get the water class of the water tile before it is cleared.*/
2551 	WaterClass wc = GetWaterClass(tile_cur);
2552 
2553 	ret = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
2554 	if (ret.Failed()) return ret;
2555 
2556 	tile_cur += TileOffsByDiagDir(direction);
2557 	if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2558 		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2559 	}
2560 
2561 	TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2562 			_dock_w_chk[direction], _dock_h_chk[direction]);
2563 
2564 	/* middle */
2565 	Station *st = nullptr;
2566 	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0), dock_area, &st);
2567 	if (ret.Failed()) return ret;
2568 
2569 	/* Distant join */
2570 	if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2571 
2572 	ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2573 	if (ret.Failed()) return ret;
2574 
2575 	if (flags & DC_EXEC) {
2576 		st->ship_station.Add(tile);
2577 		st->ship_station.Add(tile + TileOffsByDiagDir(direction));
2578 		st->AddFacility(FACIL_DOCK, tile);
2579 
2580 		st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2581 
2582 		/* If the water part of the dock is on a canal, update infrastructure counts.
2583 		 * This is needed as we've unconditionally cleared that tile before. */
2584 		if (wc == WATER_CLASS_CANAL) {
2585 			Company::Get(st->owner)->infrastructure.water++;
2586 		}
2587 		Company::Get(st->owner)->infrastructure.station += 2;
2588 
2589 		MakeDock(tile, st->owner, st->index, direction, wc);
2590 		UpdateStationDockingTiles(st);
2591 
2592 		st->AfterStationTileSetChange(true, STATION_DOCK);
2593 	}
2594 
2595 	return cost;
2596 }
2597 
RemoveDockingTile(TileIndex t)2598 void RemoveDockingTile(TileIndex t)
2599 {
2600 	for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2601 		TileIndex tile = t + TileOffsByDiagDir(d);
2602 		if (!IsValidTile(tile)) continue;
2603 
2604 		if (IsTileType(tile, MP_STATION)) {
2605 			Station *st = Station::GetByTile(tile);
2606 			if (st != nullptr) UpdateStationDockingTiles(st);
2607 		} else if (IsTileType(tile, MP_INDUSTRY)) {
2608 			Station *neutral = Industry::GetByTile(tile)->neutral_station;
2609 			if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2610 		}
2611 	}
2612 }
2613 
2614 /**
2615  * Clear docking tile status from tiles around a removed dock, if the tile has
2616  * no neighbours which would keep it as a docking tile.
2617  * @param tile Ex-dock tile to check.
2618  */
ClearDockingTilesCheckingNeighbours(TileIndex tile)2619 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2620 {
2621 	assert(IsValidTile(tile));
2622 
2623 	/* Clear and maybe re-set docking tile */
2624 	for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2625 		TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2626 		if (!IsValidTile(docking_tile)) continue;
2627 
2628 		if (IsPossibleDockingTile(docking_tile)) {
2629 			SetDockingTile(docking_tile, false);
2630 			CheckForDockingTile(docking_tile);
2631 		}
2632 	}
2633 }
2634 
2635 /**
2636  * Check if a dock tile can be docked from the given direction.
2637  * @param t Tile index of dock.
2638  * @param d DiagDirection adjacent to dock being tested. (unused)
2639  * @return True iff the dock can be docked from the given direction.
2640  */
IsValidDockingDirectionForDock(TileIndex t,DiagDirection d)2641 bool IsValidDockingDirectionForDock(TileIndex t, DiagDirection d)
2642 {
2643 	assert(IsDockTile(t));
2644 
2645 	StationGfx gfx = GetStationGfx(t);
2646 	return gfx >= GFX_DOCK_BASE_WATER_PART;
2647 }
2648 
2649 /**
2650  * Find the part of a dock that is land-based
2651  * @param t Dock tile to find land part of
2652  * @return tile of land part of dock
2653  */
FindDockLandPart(TileIndex t)2654 static TileIndex FindDockLandPart(TileIndex t)
2655 {
2656 	assert(IsDockTile(t));
2657 
2658 	StationGfx gfx = GetStationGfx(t);
2659 	if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2660 
2661 	for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2662 		TileIndex tile = t + TileOffsByDiagDir(d);
2663 		if (!IsValidTile(tile)) continue;
2664 		if (!IsDockTile(tile)) continue;
2665 		if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2666 	}
2667 
2668 	return INVALID_TILE;
2669 }
2670 
2671 /**
2672  * Remove a dock
2673  * @param tile TileIndex been queried
2674  * @param flags operation to perform
2675  * @return cost or failure of operation
2676  */
RemoveDock(TileIndex tile,DoCommandFlag flags)2677 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2678 {
2679 	Station *st = Station::GetByTile(tile);
2680 	CommandCost ret = CheckOwnership(st->owner);
2681 	if (ret.Failed()) return ret;
2682 
2683 	if (!IsDockTile(tile)) return CMD_ERROR;
2684 
2685 	TileIndex tile1 = FindDockLandPart(tile);
2686 	if (tile1 == INVALID_TILE) return CMD_ERROR;
2687 	TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2688 
2689 	ret = EnsureNoVehicleOnGround(tile1);
2690 	if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2691 	if (ret.Failed()) return ret;
2692 
2693 	if (flags & DC_EXEC) {
2694 		DoClearSquare(tile1);
2695 		MarkTileDirtyByTile(tile1);
2696 		MakeWaterKeepingClass(tile2, st->owner);
2697 
2698 		st->rect.AfterRemoveTile(st, tile1);
2699 		st->rect.AfterRemoveTile(st, tile2);
2700 
2701 		MakeShipStationAreaSmaller(st);
2702 		if (st->ship_station.tile == INVALID_TILE) {
2703 			st->ship_station.Clear();
2704 			st->docking_station.Clear();
2705 			st->facilities &= ~FACIL_DOCK;
2706 		}
2707 
2708 		Company::Get(st->owner)->infrastructure.station -= 2;
2709 
2710 		st->AfterStationTileSetChange(false, STATION_DOCK);
2711 
2712 		ClearDockingTilesCheckingNeighbours(tile1);
2713 		ClearDockingTilesCheckingNeighbours(tile2);
2714 
2715 		for (Ship *s : Ship::Iterate()) {
2716 			/* Find all ships going to our dock. */
2717 			if (s->current_order.GetDestination() != st->index) {
2718 				continue;
2719 			}
2720 
2721 			/* Find ships that are marked as "loading" but are no longer on a
2722 			 * docking tile. Force them to leave the station (as they were loading
2723 			 * on the removed dock). */
2724 			if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2725 				s->LeaveStation();
2726 			}
2727 
2728 			/* If we no longer have a dock, mark the order as invalid and send
2729 			 * the ship to the next order (or, if there is none, make it
2730 			 * wander the world). */
2731 			if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
2732 				s->SetDestTile(s->GetOrderStationLocation(st->index));
2733 			}
2734 		}
2735 	}
2736 
2737 	return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2738 }
2739 
2740 #include "table/station_land.h"
2741 
GetStationTileLayout(StationType st,byte gfx)2742 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2743 {
2744 	return &_station_display_datas[st][gfx];
2745 }
2746 
2747 /**
2748  * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2749  * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2750  * is set to the overlay to draw.
2751  * @param         ti             Positional info for the tile to decide snowyness etc. May be nullptr.
2752  * @param[in,out] ground         Groundsprite to draw.
2753  * @param[out]    overlay_offset Overlay to draw.
2754  * @return true if overlay can be drawn.
2755  */
SplitGroundSpriteForOverlay(const TileInfo * ti,SpriteID * ground,RailTrackOffset * overlay_offset)2756 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2757 {
2758 	bool snow_desert;
2759 	switch (*ground) {
2760 		case SPR_RAIL_TRACK_X:
2761 		case SPR_MONO_TRACK_X:
2762 		case SPR_MGLV_TRACK_X:
2763 			snow_desert = false;
2764 			*overlay_offset = RTO_X;
2765 			break;
2766 
2767 		case SPR_RAIL_TRACK_Y:
2768 		case SPR_MONO_TRACK_Y:
2769 		case SPR_MGLV_TRACK_Y:
2770 			snow_desert = false;
2771 			*overlay_offset = RTO_Y;
2772 			break;
2773 
2774 		case SPR_RAIL_TRACK_X_SNOW:
2775 		case SPR_MONO_TRACK_X_SNOW:
2776 		case SPR_MGLV_TRACK_X_SNOW:
2777 			snow_desert = true;
2778 			*overlay_offset = RTO_X;
2779 			break;
2780 
2781 		case SPR_RAIL_TRACK_Y_SNOW:
2782 		case SPR_MONO_TRACK_Y_SNOW:
2783 		case SPR_MGLV_TRACK_Y_SNOW:
2784 			snow_desert = true;
2785 			*overlay_offset = RTO_Y;
2786 			break;
2787 
2788 		default:
2789 			return false;
2790 	}
2791 
2792 	if (ti != nullptr) {
2793 		/* Decide snow/desert from tile */
2794 		switch (_settings_game.game_creation.landscape) {
2795 			case LT_ARCTIC:
2796 				snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2797 				break;
2798 
2799 			case LT_TROPIC:
2800 				snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2801 				break;
2802 
2803 			default:
2804 				break;
2805 		}
2806 	}
2807 
2808 	*ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2809 	return true;
2810 }
2811 
DrawTile_Station(TileInfo * ti)2812 static void DrawTile_Station(TileInfo *ti)
2813 {
2814 	const NewGRFSpriteLayout *layout = nullptr;
2815 	DrawTileSprites tmp_rail_layout;
2816 	const DrawTileSprites *t = nullptr;
2817 	int32 total_offset;
2818 	const RailtypeInfo *rti = nullptr;
2819 	uint32 relocation = 0;
2820 	uint32 ground_relocation = 0;
2821 	BaseStation *st = nullptr;
2822 	const StationSpec *statspec = nullptr;
2823 	uint tile_layout = 0;
2824 
2825 	if (HasStationRail(ti->tile)) {
2826 		rti = GetRailTypeInfo(GetRailType(ti->tile));
2827 		total_offset = rti->GetRailtypeSpriteOffset();
2828 
2829 		if (IsCustomStationSpecIndex(ti->tile)) {
2830 			/* look for customization */
2831 			st = BaseStation::GetByTile(ti->tile);
2832 			statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2833 
2834 			if (statspec != nullptr) {
2835 				tile_layout = GetStationGfx(ti->tile);
2836 
2837 				if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2838 					uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2839 					if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2840 				}
2841 
2842 				/* Ensure the chosen tile layout is valid for this custom station */
2843 				if (!statspec->renderdata.empty()) {
2844 					layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2845 					if (!layout->NeedsPreprocessing()) {
2846 						t = layout;
2847 						layout = nullptr;
2848 					}
2849 				}
2850 			}
2851 		}
2852 	} else {
2853 		total_offset = 0;
2854 	}
2855 
2856 	StationGfx gfx = GetStationGfx(ti->tile);
2857 	if (IsAirport(ti->tile)) {
2858 		gfx = GetAirportGfx(ti->tile);
2859 		if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2860 			const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2861 			if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2862 				return;
2863 			}
2864 			/* No sprite group (or no valid one) found, meaning no graphics associated.
2865 			 * Use the substitute one instead */
2866 			assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2867 			gfx = ats->grf_prop.subst_id;
2868 		}
2869 		switch (gfx) {
2870 			case APT_RADAR_GRASS_FENCE_SW:
2871 				t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2872 				break;
2873 			case APT_GRASS_FENCE_NE_FLAG:
2874 				t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2875 				break;
2876 			case APT_RADAR_FENCE_SW:
2877 				t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2878 				break;
2879 			case APT_RADAR_FENCE_NE:
2880 				t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2881 				break;
2882 			case APT_GRASS_FENCE_NE_FLAG_2:
2883 				t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2884 				break;
2885 		}
2886 	}
2887 
2888 	Owner owner = GetTileOwner(ti->tile);
2889 
2890 	PaletteID palette;
2891 	if (Company::IsValidID(owner)) {
2892 		palette = COMPANY_SPRITE_COLOUR(owner);
2893 	} else {
2894 		/* Some stations are not owner by a company, namely oil rigs */
2895 		palette = PALETTE_TO_GREY;
2896 	}
2897 
2898 	if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2899 
2900 	/* don't show foundation for docks */
2901 	if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2902 		if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2903 			/* Station has custom foundations.
2904 			 * Check whether the foundation continues beyond the tile's upper sides. */
2905 			uint edge_info = 0;
2906 			int z;
2907 			Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2908 			if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2909 			if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2910 			SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2911 			if (image == 0) goto draw_default_foundation;
2912 
2913 			if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2914 				/* Station provides extended foundations. */
2915 
2916 				static const uint8 foundation_parts[] = {
2917 					0, 0, 0, 0, // Invalid,  Invalid,   Invalid,   SLOPE_SW
2918 					0, 1, 2, 3, // Invalid,  SLOPE_EW,  SLOPE_SE,  SLOPE_WSE
2919 					0, 4, 5, 6, // Invalid,  SLOPE_NW,  SLOPE_NS,  SLOPE_NWS
2920 					7, 8, 9     // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2921 				};
2922 
2923 				AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2924 			} else {
2925 				/* Draw simple foundations, built up from 8 possible foundation sprites. */
2926 
2927 				/* Each set bit represents one of the eight composite sprites to be drawn.
2928 				 * 'Invalid' entries will not drawn but are included for completeness. */
2929 				static const uint8 composite_foundation_parts[] = {
2930 					/* Invalid  (00000000), Invalid   (11010001), Invalid   (11100100), SLOPE_SW  (11100000) */
2931 					   0x00,                0xD1,                 0xE4,                 0xE0,
2932 					/* Invalid  (11001010), SLOPE_EW  (11001001), SLOPE_SE  (11000100), SLOPE_WSE (11000000) */
2933 					   0xCA,                0xC9,                 0xC4,                 0xC0,
2934 					/* Invalid  (11010010), SLOPE_NW  (10010001), SLOPE_NS  (11100100), SLOPE_NWS (10100000) */
2935 					   0xD2,                0x91,                 0xE4,                 0xA0,
2936 					/* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2937 					   0x4A,                0x09,                 0x44
2938 				};
2939 
2940 				uint8 parts = composite_foundation_parts[ti->tileh];
2941 
2942 				/* If foundations continue beyond the tile's upper sides then
2943 				 * mask out the last two pieces. */
2944 				if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2945 				if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2946 
2947 				if (parts == 0) {
2948 					/* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2949 					 * correct offset for the childsprites.
2950 					 * So, draw the (completely empty) sprite of the default foundations. */
2951 					goto draw_default_foundation;
2952 				}
2953 
2954 				StartSpriteCombine();
2955 				for (int i = 0; i < 8; i++) {
2956 					if (HasBit(parts, i)) {
2957 						AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2958 					}
2959 				}
2960 				EndSpriteCombine();
2961 			}
2962 
2963 			OffsetGroundSprite(31, 1);
2964 			ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2965 		} else {
2966 draw_default_foundation:
2967 			DrawFoundation(ti, FOUNDATION_LEVELED);
2968 		}
2969 	}
2970 
2971 	if (IsBuoy(ti->tile)) {
2972 		DrawWaterClassGround(ti);
2973 		SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2974 		if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2975 	} else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2976 		if (ti->tileh == SLOPE_FLAT) {
2977 			DrawWaterClassGround(ti);
2978 		} else {
2979 			assert(IsDock(ti->tile));
2980 			TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2981 			WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
2982 			if (wc == WATER_CLASS_SEA) {
2983 				DrawShoreTile(ti->tileh);
2984 			} else {
2985 				DrawClearLandTile(ti, 3);
2986 			}
2987 		}
2988 	} else {
2989 		if (layout != nullptr) {
2990 			/* Sprite layout which needs preprocessing */
2991 			bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2992 			uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2993 			for (uint8 var10 : SetBitIterator(var10_values)) {
2994 				uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2995 				layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2996 			}
2997 			tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2998 			t = &tmp_rail_layout;
2999 			total_offset = 0;
3000 		} else if (statspec != nullptr) {
3001 			/* Simple sprite layout */
3002 			ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3003 			if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3004 				ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3005 			}
3006 			ground_relocation += rti->fallback_railtype;
3007 		}
3008 
3009 		SpriteID image = t->ground.sprite;
3010 		PaletteID pal  = t->ground.pal;
3011 		RailTrackOffset overlay_offset;
3012 		if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3013 			SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3014 			DrawGroundSprite(image, PAL_NONE);
3015 			DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3016 
3017 			if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3018 				SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3019 				DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3020 			}
3021 		} else {
3022 			image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3023 			if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3024 			DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3025 
3026 			/* PBS debugging, draw reserved tracks darker */
3027 			if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3028 				const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
3029 				DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3030 			}
3031 		}
3032 	}
3033 
3034 	if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3035 
3036 	if (IsRoadStop(ti->tile)) {
3037 		RoadType road_rt = GetRoadTypeRoad(ti->tile);
3038 		RoadType tram_rt = GetRoadTypeTram(ti->tile);
3039 		const RoadTypeInfo* road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3040 		const RoadTypeInfo* tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3041 
3042 		if (IsDriveThroughStopTile(ti->tile)) {
3043 			Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3044 			uint sprite_offset = axis == AXIS_X ? 1 : 0;
3045 
3046 			DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3047 		} else {
3048 			/* Non-drivethrough road stops are only valid for roads. */
3049 			assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3050 
3051 			if (road_rti->UsesOverlay()) {
3052 				DiagDirection dir = GetRoadStopDir(ti->tile);
3053 				SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3054 				DrawGroundSprite(ground + dir, PAL_NONE);
3055 			}
3056 		}
3057 
3058 		/* Draw road, tram catenary */
3059 		DrawRoadCatenary(ti);
3060 	}
3061 
3062 	if (IsRailWaypoint(ti->tile)) {
3063 		/* Don't offset the waypoint graphics; they're always the same. */
3064 		total_offset = 0;
3065 	}
3066 
3067 	DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3068 }
3069 
StationPickerDrawSprite(int x,int y,StationType st,RailType railtype,RoadType roadtype,int image)3070 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3071 {
3072 	int32 total_offset = 0;
3073 	PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3074 	const DrawTileSprites *t = GetStationTileLayout(st, image);
3075 	const RailtypeInfo *rti = nullptr;
3076 
3077 	if (railtype != INVALID_RAILTYPE) {
3078 		rti = GetRailTypeInfo(railtype);
3079 		total_offset = rti->GetRailtypeSpriteOffset();
3080 	}
3081 
3082 	SpriteID img = t->ground.sprite;
3083 	RailTrackOffset overlay_offset;
3084 	if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3085 		SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
3086 		DrawSprite(img, PAL_NONE, x, y);
3087 		DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3088 	} else {
3089 		DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3090 	}
3091 
3092 	if (roadtype != INVALID_ROADTYPE) {
3093 		const RoadTypeInfo* rti = GetRoadTypeInfo(roadtype);
3094 		if (image >= 4) {
3095 			/* Drive-through stop */
3096 			uint sprite_offset = 5 - image;
3097 
3098 			/* Road underlay takes precedence over tram */
3099 			if (rti->UsesOverlay()) {
3100 				SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_GROUND);
3101 				DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3102 
3103 				SpriteID overlay = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_OVERLAY);
3104 				if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3105 			} else if (RoadTypeIsTram(roadtype)) {
3106 				DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3107 			}
3108 		} else {
3109 			/* Drive-in stop */
3110 			if (RoadTypeIsRoad(roadtype) && rti->UsesOverlay()) {
3111 				SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_ROADSTOP);
3112 				DrawSprite(ground + image, PAL_NONE, x, y);
3113 			}
3114 		}
3115 	}
3116 
3117 	/* Default waypoint has no railtype specific sprites */
3118 	DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
3119 }
3120 
GetSlopePixelZ_Station(TileIndex tile,uint x,uint y)3121 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
3122 {
3123 	return GetTileMaxPixelZ(tile);
3124 }
3125 
GetFoundation_Station(TileIndex tile,Slope tileh)3126 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
3127 {
3128 	return FlatteningFoundation(tileh);
3129 }
3130 
GetTileDesc_Station(TileIndex tile,TileDesc * td)3131 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3132 {
3133 	td->owner[0] = GetTileOwner(tile);
3134 
3135 	if (IsRoadStopTile(tile)) {
3136 		RoadType road_rt = GetRoadTypeRoad(tile);
3137 		RoadType tram_rt = GetRoadTypeTram(tile);
3138 		Owner road_owner = INVALID_OWNER;
3139 		Owner tram_owner = INVALID_OWNER;
3140 		if (road_rt != INVALID_ROADTYPE) {
3141 			const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3142 			td->roadtype = rti->strings.name;
3143 			td->road_speed = rti->max_speed / 2;
3144 			road_owner = GetRoadOwner(tile, RTT_ROAD);
3145 		}
3146 
3147 		if (tram_rt != INVALID_ROADTYPE) {
3148 			const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3149 			td->tramtype = rti->strings.name;
3150 			td->tram_speed = rti->max_speed / 2;
3151 			tram_owner = GetRoadOwner(tile, RTT_TRAM);
3152 		}
3153 
3154 		if (IsDriveThroughStopTile(tile)) {
3155 			/* Is there a mix of owners? */
3156 			if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3157 					(road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3158 				uint i = 1;
3159 				if (road_owner != INVALID_OWNER) {
3160 					td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3161 					td->owner[i] = road_owner;
3162 					i++;
3163 				}
3164 				if (tram_owner != INVALID_OWNER) {
3165 					td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3166 					td->owner[i] = tram_owner;
3167 				}
3168 			}
3169 		}
3170 	}
3171 
3172 	td->build_date = BaseStation::GetByTile(tile)->build_date;
3173 
3174 	if (HasStationTileRail(tile)) {
3175 		const StationSpec *spec = GetStationSpec(tile);
3176 
3177 		if (spec != nullptr) {
3178 			td->station_class = StationClass::Get(spec->cls_id)->name;
3179 			td->station_name  = spec->name;
3180 
3181 			if (spec->grf_prop.grffile != nullptr) {
3182 				const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3183 				td->grf = gc->GetName();
3184 			}
3185 		}
3186 
3187 		const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3188 		td->rail_speed = rti->max_speed;
3189 		td->railtype = rti->strings.name;
3190 	}
3191 
3192 	if (IsAirport(tile)) {
3193 		const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3194 		td->airport_class = AirportClass::Get(as->cls_id)->name;
3195 		td->airport_name = as->name;
3196 
3197 		const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3198 		td->airport_tile_name = ats->name;
3199 
3200 		if (as->grf_prop.grffile != nullptr) {
3201 			const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3202 			td->grf = gc->GetName();
3203 		} else if (ats->grf_prop.grffile != nullptr) {
3204 			const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3205 			td->grf = gc->GetName();
3206 		}
3207 	}
3208 
3209 	StringID str;
3210 	switch (GetStationType(tile)) {
3211 		default: NOT_REACHED();
3212 		case STATION_RAIL:     str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3213 		case STATION_AIRPORT:
3214 			str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3215 			break;
3216 		case STATION_TRUCK:    str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3217 		case STATION_BUS:      str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3218 		case STATION_OILRIG: {
3219 			const Industry *i = Station::GetByTile(tile)->industry;
3220 			const IndustrySpec *is = GetIndustrySpec(i->type);
3221 			td->owner[0] = i->owner;
3222 			str = is->name;
3223 			if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3224 			break;
3225 		}
3226 		case STATION_DOCK:     str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3227 		case STATION_BUOY:     str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3228 		case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3229 	}
3230 	td->str = str;
3231 }
3232 
3233 
GetTileTrackStatus_Station(TileIndex tile,TransportType mode,uint sub_mode,DiagDirection side)3234 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3235 {
3236 	TrackBits trackbits = TRACK_BIT_NONE;
3237 
3238 	switch (mode) {
3239 		case TRANSPORT_RAIL:
3240 			if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3241 				trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3242 			}
3243 			break;
3244 
3245 		case TRANSPORT_WATER:
3246 			/* buoy is coded as a station, it is always on open water */
3247 			if (IsBuoy(tile)) {
3248 				trackbits = TRACK_BIT_ALL;
3249 				/* remove tracks that connect NE map edge */
3250 				if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3251 				/* remove tracks that connect NW map edge */
3252 				if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3253 			}
3254 			break;
3255 
3256 		case TRANSPORT_ROAD:
3257 			if (IsRoadStop(tile)) {
3258 				RoadTramType rtt = (RoadTramType)sub_mode;
3259 				if (!HasTileRoadType(tile, rtt)) break;
3260 
3261 				DiagDirection dir = GetRoadStopDir(tile);
3262 				Axis axis = DiagDirToAxis(dir);
3263 
3264 				if (side != INVALID_DIAGDIR) {
3265 					if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
3266 				}
3267 
3268 				trackbits = AxisToTrackBits(axis);
3269 			}
3270 			break;
3271 
3272 		default:
3273 			break;
3274 	}
3275 
3276 	return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3277 }
3278 
3279 
TileLoop_Station(TileIndex tile)3280 static void TileLoop_Station(TileIndex tile)
3281 {
3282 	/* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3283 	 * hardcoded.....not good */
3284 	switch (GetStationType(tile)) {
3285 		case STATION_AIRPORT:
3286 			AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3287 			break;
3288 
3289 		case STATION_DOCK:
3290 			if (!IsTileFlat(tile)) break; // only handle water part
3291 			FALLTHROUGH;
3292 
3293 		case STATION_OILRIG: //(station part)
3294 		case STATION_BUOY:
3295 			TileLoop_Water(tile);
3296 			break;
3297 
3298 		default: break;
3299 	}
3300 }
3301 
3302 
AnimateTile_Station(TileIndex tile)3303 static void AnimateTile_Station(TileIndex tile)
3304 {
3305 	if (HasStationRail(tile)) {
3306 		AnimateStationTile(tile);
3307 		return;
3308 	}
3309 
3310 	if (IsAirport(tile)) {
3311 		AnimateAirportTile(tile);
3312 	}
3313 }
3314 
3315 
ClickTile_Station(TileIndex tile)3316 static bool ClickTile_Station(TileIndex tile)
3317 {
3318 	const BaseStation *bst = BaseStation::GetByTile(tile);
3319 
3320 	if (bst->facilities & FACIL_WAYPOINT) {
3321 		ShowWaypointWindow(Waypoint::From(bst));
3322 	} else if (IsHangar(tile)) {
3323 		const Station *st = Station::From(bst);
3324 		ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3325 	} else {
3326 		ShowStationViewWindow(bst->index);
3327 	}
3328 	return true;
3329 }
3330 
VehicleEnter_Station(Vehicle * v,TileIndex tile,int x,int y)3331 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3332 {
3333 	if (v->type == VEH_TRAIN) {
3334 		StationID station_id = GetStationIndex(tile);
3335 		if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3336 		if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3337 
3338 		int station_ahead;
3339 		int station_length;
3340 		int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3341 
3342 		/* Stop whenever that amount of station ahead + the distance from the
3343 		 * begin of the platform to the stop location is longer than the length
3344 		 * of the platform. Station ahead 'includes' the current tile where the
3345 		 * vehicle is on, so we need to subtract that. */
3346 		if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3347 
3348 		DiagDirection dir = DirToDiagDir(v->direction);
3349 
3350 		x &= 0xF;
3351 		y &= 0xF;
3352 
3353 		if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3354 		if (y == TILE_SIZE / 2) {
3355 			if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3356 			stop &= TILE_SIZE - 1;
3357 
3358 			if (x == stop) {
3359 				return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3360 			} else if (x < stop) {
3361 				v->vehstatus |= VS_TRAIN_SLOWING;
3362 				uint16 spd = std::max(0, (stop - x) * 20 - 15);
3363 				if (spd < v->cur_speed) v->cur_speed = spd;
3364 			}
3365 		}
3366 	} else if (v->type == VEH_ROAD) {
3367 		RoadVehicle *rv = RoadVehicle::From(v);
3368 		if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3369 			if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3370 				/* Attempt to allocate a parking bay in a road stop */
3371 				return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3372 			}
3373 		}
3374 	}
3375 
3376 	return VETSB_CONTINUE;
3377 }
3378 
3379 /**
3380  * Run the watched cargo callback for all houses in the catchment area.
3381  * @param st Station.
3382  */
TriggerWatchedCargoCallbacks(Station * st)3383 void TriggerWatchedCargoCallbacks(Station *st)
3384 {
3385 	/* Collect cargoes accepted since the last big tick. */
3386 	CargoTypes cargoes = 0;
3387 	for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3388 		if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3389 	}
3390 
3391 	/* Anything to do? */
3392 	if (cargoes == 0) return;
3393 
3394 	/* Loop over all houses in the catchment. */
3395 	BitmapTileIterator it(st->catchment_tiles);
3396 	for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3397 		if (IsTileType(tile, MP_HOUSE)) {
3398 			WatchedCargoCallback(tile, cargoes);
3399 		}
3400 	}
3401 }
3402 
3403 /**
3404  * This function is called for each station once every 250 ticks.
3405  * Not all stations will get the tick at the same time.
3406  * @param st the station receiving the tick.
3407  * @return true if the station is still valid (wasn't deleted)
3408  */
StationHandleBigTick(BaseStation * st)3409 static bool StationHandleBigTick(BaseStation *st)
3410 {
3411 	if (!st->IsInUse()) {
3412 		if (++st->delete_ctr >= 8) delete st;
3413 		return false;
3414 	}
3415 
3416 	if (Station::IsExpected(st)) {
3417 		TriggerWatchedCargoCallbacks(Station::From(st));
3418 
3419 		for (CargoID i = 0; i < NUM_CARGO; i++) {
3420 			ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3421 		}
3422 	}
3423 
3424 
3425 	if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3426 
3427 	return true;
3428 }
3429 
byte_inc_sat(byte * p)3430 static inline void byte_inc_sat(byte *p)
3431 {
3432 	byte b = *p + 1;
3433 	if (b != 0) *p = b;
3434 }
3435 
3436 /**
3437  * Truncate the cargo by a specific amount.
3438  * @param cs The type of cargo to perform the truncation for.
3439  * @param ge The goods entry, of the station, to truncate.
3440  * @param amount The amount to truncate the cargo by.
3441  */
TruncateCargo(const CargoSpec * cs,GoodsEntry * ge,uint amount=UINT_MAX)3442 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3443 {
3444 	/* If truncating also punish the source stations' ratings to
3445 	 * decrease the flow of incoming cargo. */
3446 
3447 	StationCargoAmountMap waiting_per_source;
3448 	ge->cargo.Truncate(amount, &waiting_per_source);
3449 	for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3450 		Station *source_station = Station::GetIfValid(i->first);
3451 		if (source_station == nullptr) continue;
3452 
3453 		GoodsEntry &source_ge = source_station->goods[cs->Index()];
3454 		source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3455 	}
3456 }
3457 
UpdateStationRating(Station * st)3458 static void UpdateStationRating(Station *st)
3459 {
3460 	bool waiting_changed = false;
3461 
3462 	byte_inc_sat(&st->time_since_load);
3463 	byte_inc_sat(&st->time_since_unload);
3464 
3465 	for (const CargoSpec *cs : CargoSpec::Iterate()) {
3466 		GoodsEntry *ge = &st->goods[cs->Index()];
3467 		/* Slowly increase the rating back to its original level in the case we
3468 		 *  didn't deliver cargo yet to this station. This happens when a bribe
3469 		 *  failed while you didn't moved that cargo yet to a station. */
3470 		if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3471 			ge->rating++;
3472 		}
3473 
3474 		/* Only change the rating if we are moving this cargo */
3475 		if (ge->HasRating()) {
3476 			byte_inc_sat(&ge->time_since_pickup);
3477 			if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3478 				ClrBit(ge->status, GoodsEntry::GES_RATING);
3479 				ge->last_speed = 0;
3480 				TruncateCargo(cs, ge);
3481 				waiting_changed = true;
3482 				continue;
3483 			}
3484 
3485 			bool skip = false;
3486 			int rating = 0;
3487 			uint waiting = ge->cargo.AvailableCount();
3488 
3489 			/* num_dests is at least 1 if there is any cargo as
3490 			 * INVALID_STATION is also a destination.
3491 			 */
3492 			uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3493 
3494 			/* Average amount of cargo per next hop, but prefer solitary stations
3495 			 * with only one or two next hops. They are allowed to have more
3496 			 * cargo waiting per next hop.
3497 			 * With manual cargo distribution waiting_avg = waiting / 2 as then
3498 			 * INVALID_STATION is the only destination.
3499 			 */
3500 			uint waiting_avg = waiting / (num_dests + 1);
3501 
3502 			if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3503 				/* Perform custom station rating. If it succeeds the speed, days in transit and
3504 				 * waiting cargo ratings must not be executed. */
3505 
3506 				/* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3507 				uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3508 
3509 				uint32 var18 = std::min<uint>(ge->time_since_pickup, 0xFFu)
3510 					| (std::min<uint>(ge->max_waiting_cargo, 0xFFFFu) << 8)
3511 					| (std::min<uint>(last_speed, 0xFFu) << 24);
3512 				/* Convert to the 'old' vehicle types */
3513 				uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3514 				uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3515 				if (callback != CALLBACK_FAILED) {
3516 					skip = true;
3517 					rating = GB(callback, 0, 14);
3518 
3519 					/* Simulate a 15 bit signed value */
3520 					if (HasBit(callback, 14)) rating -= 0x4000;
3521 				}
3522 			}
3523 
3524 			if (!skip) {
3525 				int b = ge->last_speed - 85;
3526 				if (b >= 0) rating += b >> 2;
3527 
3528 				byte waittime = ge->time_since_pickup;
3529 				if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3530 				if (waittime <= 21) rating += 25;
3531 				if (waittime <= 12) rating += 25;
3532 				if (waittime <= 6) rating += 45;
3533 				if (waittime <= 3) rating += 35;
3534 
3535 				rating -= 90;
3536 				if (ge->max_waiting_cargo <= 1500) rating += 55;
3537 				if (ge->max_waiting_cargo <= 1000) rating += 35;
3538 				if (ge->max_waiting_cargo <= 600) rating += 10;
3539 				if (ge->max_waiting_cargo <= 300) rating += 20;
3540 				if (ge->max_waiting_cargo <= 100) rating += 10;
3541 			}
3542 
3543 			if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3544 
3545 			byte age = ge->last_age;
3546 			if (age < 3) rating += 10;
3547 			if (age < 2) rating += 10;
3548 			if (age < 1) rating += 13;
3549 
3550 			{
3551 				int or_ = ge->rating; // old rating
3552 
3553 				/* only modify rating in steps of -2, -1, 0, 1 or 2 */
3554 				ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3555 
3556 				/* if rating is <= 64 and more than 100 items waiting on average per destination,
3557 				 * remove some random amount of goods from the station */
3558 				if (rating <= 64 && waiting_avg >= 100) {
3559 					int dec = Random() & 0x1F;
3560 					if (waiting_avg < 200) dec &= 7;
3561 					waiting -= (dec + 1) * num_dests;
3562 					waiting_changed = true;
3563 				}
3564 
3565 				/* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3566 				if (rating <= 127 && waiting != 0) {
3567 					uint32 r = Random();
3568 					if (rating <= (int)GB(r, 0, 7)) {
3569 						/* Need to have int, otherwise it will just overflow etc. */
3570 						waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3571 						waiting_changed = true;
3572 					}
3573 				}
3574 
3575 				/* At some point we really must cap the cargo. Previously this
3576 				 * was a strict 4095, but now we'll have a less strict, but
3577 				 * increasingly aggressive truncation of the amount of cargo. */
3578 				static const uint WAITING_CARGO_THRESHOLD  = 1 << 12;
3579 				static const uint WAITING_CARGO_CUT_FACTOR = 1 <<  6;
3580 				static const uint MAX_WAITING_CARGO        = 1 << 15;
3581 
3582 				if (waiting > WAITING_CARGO_THRESHOLD) {
3583 					uint difference = waiting - WAITING_CARGO_THRESHOLD;
3584 					waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3585 
3586 					waiting = std::min(waiting, MAX_WAITING_CARGO);
3587 					waiting_changed = true;
3588 				}
3589 
3590 				/* We can't truncate cargo that's already reserved for loading.
3591 				 * Thus StoredCount() here. */
3592 				if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3593 					/* Feed back the exact own waiting cargo at this station for the
3594 					 * next rating calculation. */
3595 					ge->max_waiting_cargo = 0;
3596 
3597 					TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3598 				} else {
3599 					/* If the average number per next hop is low, be more forgiving. */
3600 					ge->max_waiting_cargo = waiting_avg;
3601 				}
3602 			}
3603 		}
3604 	}
3605 
3606 	StationID index = st->index;
3607 	if (waiting_changed) {
3608 		SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3609 	} else {
3610 		SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3611 	}
3612 }
3613 
3614 /**
3615  * Reroute cargo of type c at station st or in any vehicles unloading there.
3616  * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3617  * @param st Station to be rerouted at.
3618  * @param c Type of cargo.
3619  * @param avoid Original next hop of cargo, avoid this.
3620  * @param avoid2 Another station to be avoided when rerouting.
3621  */
RerouteCargo(Station * st,CargoID c,StationID avoid,StationID avoid2)3622 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3623 {
3624 	GoodsEntry &ge = st->goods[c];
3625 
3626 	/* Reroute cargo in station. */
3627 	ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3628 
3629 	/* Reroute cargo staged to be transferred. */
3630 	for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3631 		for (Vehicle *v = *it; v != nullptr; v = v->Next()) {
3632 			if (v->cargo_type != c) continue;
3633 			v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3634 		}
3635 	}
3636 }
3637 
3638 /**
3639  * Check all next hops of cargo packets in this station for existence of a
3640  * a valid link they may use to travel on. Reroute any cargo not having a valid
3641  * link and remove timed out links found like this from the linkgraph. We're
3642  * not all links here as that is expensive and useless. A link no one is using
3643  * doesn't hurt either.
3644  * @param from Station to check.
3645  */
DeleteStaleLinks(Station * from)3646 void DeleteStaleLinks(Station *from)
3647 {
3648 	for (CargoID c = 0; c < NUM_CARGO; ++c) {
3649 		const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
3650 		GoodsEntry &ge = from->goods[c];
3651 		LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3652 		if (lg == nullptr) continue;
3653 		Node node = (*lg)[ge.node];
3654 		for (EdgeIterator it(node.Begin()); it != node.End();) {
3655 			Edge edge = it->second;
3656 			Station *to = Station::Get((*lg)[it->first].Station());
3657 			assert(to->goods[c].node == it->first);
3658 			++it; // Do that before removing the edge. Anything else may crash.
3659 			assert(_date >= edge.LastUpdate());
3660 			uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3661 			if ((uint)(_date - edge.LastUpdate()) > timeout) {
3662 				bool updated = false;
3663 
3664 				if (auto_distributed) {
3665 					/* Have all vehicles refresh their next hops before deciding to
3666 					 * remove the node. */
3667 					std::vector<Vehicle *> vehicles;
3668 					for (OrderList *l : OrderList::Iterate()) {
3669 						bool found_from = false;
3670 						bool found_to = false;
3671 						for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
3672 							if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3673 							if (order->GetDestination() == from->index) {
3674 								found_from = true;
3675 								if (found_to) break;
3676 							} else if (order->GetDestination() == to->index) {
3677 								found_to = true;
3678 								if (found_from) break;
3679 							}
3680 						}
3681 						if (!found_to || !found_from) continue;
3682 						vehicles.push_back(l->GetFirstSharedVehicle());
3683 					}
3684 
3685 					auto iter = vehicles.begin();
3686 					while (iter != vehicles.end()) {
3687 						Vehicle *v = *iter;
3688 						/* Do not refresh links of vehicles that have been stopped in depot for a long time. */
3689 						if (!v->IsStoppedInDepot() || static_cast<uint>(_date - v->date_of_last_service) <=
3690 								LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
3691 							LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3692 						}
3693 						if (edge.LastUpdate() == _date) {
3694 							updated = true;
3695 							break;
3696 						}
3697 
3698 						Vehicle *next_shared = v->NextShared();
3699 						if (next_shared) {
3700 							*iter = next_shared;
3701 							++iter;
3702 						} else {
3703 							iter = vehicles.erase(iter);
3704 						}
3705 
3706 						if (iter == vehicles.end()) iter = vehicles.begin();
3707 					}
3708 				}
3709 
3710 				if (!updated) {
3711 					/* If it's still considered dead remove it. */
3712 					node.RemoveEdge(to->goods[c].node);
3713 					ge.flows.DeleteFlows(to->index);
3714 					RerouteCargo(from, c, to->index, from->index);
3715 				}
3716 			} else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3717 				edge.Restrict();
3718 				ge.flows.RestrictFlows(to->index);
3719 				RerouteCargo(from, c, to->index, from->index);
3720 			} else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3721 				edge.Release();
3722 			}
3723 		}
3724 		assert(_date >= lg->LastCompression());
3725 		if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3726 			lg->Compress();
3727 		}
3728 	}
3729 }
3730 
3731 /**
3732  * Increase capacity for a link stat given by station cargo and next hop.
3733  * @param st Station to get the link stats from.
3734  * @param cargo Cargo to increase stat for.
3735  * @param next_station_id Station the consist will be travelling to next.
3736  * @param capacity Capacity to add to link stat.
3737  * @param usage Usage to add to link stat.
3738  * @param mode Update mode to be applied.
3739  */
IncreaseStats(Station * st,CargoID cargo,StationID next_station_id,uint capacity,uint usage,uint32 time,EdgeUpdateMode mode)3740 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32 time, EdgeUpdateMode mode)
3741 {
3742 	GoodsEntry &ge1 = st->goods[cargo];
3743 	Station *st2 = Station::Get(next_station_id);
3744 	GoodsEntry &ge2 = st2->goods[cargo];
3745 	LinkGraph *lg = nullptr;
3746 	if (ge1.link_graph == INVALID_LINK_GRAPH) {
3747 		if (ge2.link_graph == INVALID_LINK_GRAPH) {
3748 			if (LinkGraph::CanAllocateItem()) {
3749 				lg = new LinkGraph(cargo);
3750 				LinkGraphSchedule::instance.Queue(lg);
3751 				ge2.link_graph = lg->index;
3752 				ge2.node = lg->AddNode(st2);
3753 			} else {
3754 				Debug(misc, 0, "Can't allocate link graph");
3755 			}
3756 		} else {
3757 			lg = LinkGraph::Get(ge2.link_graph);
3758 		}
3759 		if (lg) {
3760 			ge1.link_graph = lg->index;
3761 			ge1.node = lg->AddNode(st);
3762 		}
3763 	} else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3764 		lg = LinkGraph::Get(ge1.link_graph);
3765 		ge2.link_graph = lg->index;
3766 		ge2.node = lg->AddNode(st2);
3767 	} else {
3768 		lg = LinkGraph::Get(ge1.link_graph);
3769 		if (ge1.link_graph != ge2.link_graph) {
3770 			LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3771 			if (lg->Size() < lg2->Size()) {
3772 				LinkGraphSchedule::instance.Unqueue(lg);
3773 				lg2->Merge(lg); // Updates GoodsEntries of lg
3774 				lg = lg2;
3775 			} else {
3776 				LinkGraphSchedule::instance.Unqueue(lg2);
3777 				lg->Merge(lg2); // Updates GoodsEntries of lg2
3778 			}
3779 		}
3780 	}
3781 	if (lg != nullptr) {
3782 		(*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
3783 	}
3784 }
3785 
3786 /**
3787  * Increase capacity for all link stats associated with vehicles in the given consist.
3788  * @param st Station to get the link stats from.
3789  * @param front First vehicle in the consist.
3790  * @param next_station_id Station the consist will be travelling to next.
3791  */
IncreaseStats(Station * st,const Vehicle * front,StationID next_station_id,uint32 time)3792 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32 time)
3793 {
3794 	for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
3795 		if (v->refit_cap > 0) {
3796 			/* The cargo count can indeed be higher than the refit_cap if
3797 			 * wagons have been auto-replaced and subsequently auto-
3798 			 * refitted to a higher capacity. The cargo gets redistributed
3799 			 * among the wagons in that case.
3800 			 * As usage is not such an important figure anyway we just
3801 			 * ignore the additional cargo then.*/
3802 			IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3803 					std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
3804 		}
3805 	}
3806 }
3807 
3808 /* called for every station each tick */
StationHandleSmallTick(BaseStation * st)3809 static void StationHandleSmallTick(BaseStation *st)
3810 {
3811 	if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3812 
3813 	byte b = st->delete_ctr + 1;
3814 	if (b >= STATION_RATING_TICKS) b = 0;
3815 	st->delete_ctr = b;
3816 
3817 	if (b == 0) UpdateStationRating(Station::From(st));
3818 }
3819 
OnTick_Station()3820 void OnTick_Station()
3821 {
3822 	if (_game_mode == GM_EDITOR) return;
3823 
3824 	for (BaseStation *st : BaseStation::Iterate()) {
3825 		StationHandleSmallTick(st);
3826 
3827 		/* Clean up the link graph about once a week. */
3828 		if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3829 			DeleteStaleLinks(Station::From(st));
3830 		};
3831 
3832 		/* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3833 		 * Station index is included so that triggers are not all done
3834 		 * at the same time. */
3835 		if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3836 			/* Stop processing this station if it was deleted */
3837 			if (!StationHandleBigTick(st)) continue;
3838 			TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3839 			if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3840 		}
3841 	}
3842 }
3843 
3844 /** Monthly loop for stations. */
StationMonthlyLoop()3845 void StationMonthlyLoop()
3846 {
3847 	for (Station *st : Station::Iterate()) {
3848 		for (CargoID i = 0; i < NUM_CARGO; i++) {
3849 			GoodsEntry *ge = &st->goods[i];
3850 			SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3851 			ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3852 		}
3853 	}
3854 }
3855 
3856 
ModifyStationRatingAround(TileIndex tile,Owner owner,int amount,uint radius)3857 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3858 {
3859 	ForAllStationsRadius(tile, radius, [&](Station *st) {
3860 		if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
3861 			for (CargoID i = 0; i < NUM_CARGO; i++) {
3862 				GoodsEntry *ge = &st->goods[i];
3863 
3864 				if (ge->status != 0) {
3865 					ge->rating = Clamp(ge->rating + amount, 0, 255);
3866 				}
3867 			}
3868 		}
3869 	});
3870 }
3871 
UpdateStationWaiting(Station * st,CargoID type,uint amount,SourceType source_type,SourceID source_id)3872 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3873 {
3874 	/* We can't allocate a CargoPacket? Then don't do anything
3875 	 * at all; i.e. just discard the incoming cargo. */
3876 	if (!CargoPacket::CanAllocateItem()) return 0;
3877 
3878 	GoodsEntry &ge = st->goods[type];
3879 	amount += ge.amount_fract;
3880 	ge.amount_fract = GB(amount, 0, 8);
3881 
3882 	amount >>= 8;
3883 	/* No new "real" cargo item yet. */
3884 	if (amount == 0) return 0;
3885 
3886 	StationID next = ge.GetVia(st->index);
3887 	ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3888 	LinkGraph *lg = nullptr;
3889 	if (ge.link_graph == INVALID_LINK_GRAPH) {
3890 		if (LinkGraph::CanAllocateItem()) {
3891 			lg = new LinkGraph(type);
3892 			LinkGraphSchedule::instance.Queue(lg);
3893 			ge.link_graph = lg->index;
3894 			ge.node = lg->AddNode(st);
3895 		} else {
3896 			Debug(misc, 0, "Can't allocate link graph");
3897 		}
3898 	} else {
3899 		lg = LinkGraph::Get(ge.link_graph);
3900 	}
3901 	if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
3902 
3903 	if (!ge.HasRating()) {
3904 		InvalidateWindowData(WC_STATION_LIST, st->index);
3905 		SetBit(ge.status, GoodsEntry::GES_RATING);
3906 	}
3907 
3908 	TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3909 	TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3910 	AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3911 
3912 	SetWindowDirty(WC_STATION_VIEW, st->index);
3913 	st->MarkTilesDirty(true);
3914 	return amount;
3915 }
3916 
IsUniqueStationName(const std::string & name)3917 static bool IsUniqueStationName(const std::string &name)
3918 {
3919 	for (const Station *st : Station::Iterate()) {
3920 		if (!st->name.empty() && st->name == name) return false;
3921 	}
3922 
3923 	return true;
3924 }
3925 
3926 /**
3927  * Rename a station
3928  * @param tile unused
3929  * @param flags operation to perform
3930  * @param p1 station ID that is to be renamed
3931  * @param p2 unused
3932  * @param text the new name or an empty string when resetting to the default
3933  * @return the cost of this operation or an error
3934  */
CmdRenameStation(TileIndex tile,DoCommandFlag flags,uint32 p1,uint32 p2,const std::string & text)3935 CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
3936 {
3937 	Station *st = Station::GetIfValid(p1);
3938 	if (st == nullptr) return CMD_ERROR;
3939 
3940 	CommandCost ret = CheckOwnership(st->owner);
3941 	if (ret.Failed()) return ret;
3942 
3943 	bool reset = text.empty();
3944 
3945 	if (!reset) {
3946 		if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3947 		if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3948 	}
3949 
3950 	if (flags & DC_EXEC) {
3951 		st->cached_name.clear();
3952 		if (reset) {
3953 			st->name.clear();
3954 		} else {
3955 			st->name = text;
3956 		}
3957 
3958 		st->UpdateVirtCoord();
3959 		InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3960 	}
3961 
3962 	return CommandCost();
3963 }
3964 
AddNearbyStationsByCatchment(TileIndex tile,StationList * stations,StationList & nearby)3965 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
3966 {
3967 	for (Station *st : nearby) {
3968 		if (st->TileIsInCatchment(tile)) stations->insert(st);
3969 	}
3970 }
3971 
3972 /**
3973  * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3974  * @return pointer to a StationList containing all stations found
3975  */
GetStations()3976 const StationList *StationFinder::GetStations()
3977 {
3978 	if (this->tile != INVALID_TILE) {
3979 		if (IsTileType(this->tile, MP_HOUSE)) {
3980 			/* Town nearby stations need to be filtered per tile. */
3981 			assert(this->w == 1 && this->h == 1);
3982 			AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
3983 		} else {
3984 			ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex tile) {
3985 				this->stations.insert(st);
3986 				return true;
3987 			});
3988 		}
3989 		this->tile = INVALID_TILE;
3990 	}
3991 	return &this->stations;
3992 }
3993 
3994 
CanMoveGoodsToStation(const Station * st,CargoID type)3995 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
3996 {
3997 	/* Is the station reserved exclusively for somebody else? */
3998 	if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
3999 
4000 	/* Lowest possible rating, better not to give cargo anymore. */
4001 	if (st->goods[type].rating == 0) return false;
4002 
4003 	/* Selectively servicing stations, and not this one. */
4004 	if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4005 
4006 	if (IsCargoInClass(type, CC_PASSENGERS)) {
4007 		/* Passengers are never served by just a truck stop. */
4008 		if (st->facilities == FACIL_TRUCK_STOP) return false;
4009 	} else {
4010 		/* Non-passengers are never served by just a bus stop. */
4011 		if (st->facilities == FACIL_BUS_STOP) return false;
4012 	}
4013 	return true;
4014 }
4015 
MoveGoodsToStation(CargoID type,uint amount,SourceType source_type,SourceID source_id,const StationList * all_stations,Owner exclusivity)4016 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4017 {
4018 	/* Return if nothing to do. Also the rounding below fails for 0. */
4019 	if (all_stations->empty()) return 0;
4020 	if (amount == 0) return 0;
4021 
4022 	Station *first_station = nullptr;
4023 	typedef std::pair<Station *, uint> StationInfo;
4024 	std::vector<StationInfo> used_stations;
4025 
4026 	for (Station *st : *all_stations) {
4027 		if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4028 		if (!CanMoveGoodsToStation(st, type)) continue;
4029 
4030 		/* Avoid allocating a vector if there is only one station to significantly
4031 		 * improve performance in this common case. */
4032 		if (first_station == nullptr) {
4033 			first_station = st;
4034 			continue;
4035 		}
4036 		if (used_stations.empty()) {
4037 			used_stations.reserve(2);
4038 			used_stations.emplace_back(std::make_pair(first_station, 0));
4039 		}
4040 		used_stations.emplace_back(std::make_pair(st, 0));
4041 	}
4042 
4043 	/* no stations around at all? */
4044 	if (first_station == nullptr) return 0;
4045 
4046 	if (used_stations.empty()) {
4047 		/* only one station around */
4048 		amount *= first_station->goods[type].rating + 1;
4049 		return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4050 	}
4051 
4052 	uint company_best[OWNER_NONE + 1] = {};  // best rating for each company, including OWNER_NONE
4053 	uint company_sum[OWNER_NONE + 1] = {};   // sum of ratings for each company
4054 	uint best_rating = 0;
4055 	uint best_sum = 0;  // sum of best ratings for each company
4056 
4057 	for (auto &p : used_stations) {
4058 		auto owner = p.first->owner;
4059 		auto rating = p.first->goods[type].rating;
4060 		if (rating > company_best[owner]) {
4061 			best_sum += rating - company_best[owner];  // it's usually faster than iterating companies later
4062 			company_best[owner] = rating;
4063 			if (rating > best_rating) best_rating = rating;
4064 		}
4065 		company_sum[owner] += rating;
4066 	}
4067 
4068 	/* From now we'll calculate with fractional cargo amounts.
4069 	 * First determine how much cargo we really have. */
4070 	amount *= best_rating + 1;
4071 
4072 	uint moving = 0;
4073 	for (auto &p : used_stations) {
4074 		uint owner = p.first->owner;
4075 		/* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4076 		 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4077 		p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4078 		moving += p.second;
4079 	}
4080 
4081 	/* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4082 	if (amount > moving) {
4083 		std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4084 			return b.first->goods[type].rating < a.first->goods[type].rating;
4085 		});
4086 
4087 		assert(amount - moving <= used_stations.size());
4088 		for (uint i = 0; i < amount - moving; i++) {
4089 			used_stations[i].second++;
4090 		}
4091 	}
4092 
4093 	uint moved = 0;
4094 	for (auto &p : used_stations) {
4095 		moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4096 	}
4097 
4098 	return moved;
4099 }
4100 
UpdateStationDockingTiles(Station * st)4101 void UpdateStationDockingTiles(Station *st)
4102 {
4103 	st->docking_station.Clear();
4104 
4105 	/* For neutral stations, start with the industry area instead of dock area */
4106 	const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4107 
4108 	if (area->tile == INVALID_TILE) return;
4109 
4110 	int x = TileX(area->tile);
4111 	int y = TileY(area->tile);
4112 
4113 	/* Expand the area by a tile on each side while
4114 	 * making sure that we remain inside the map. */
4115 	int x2 = std::min<int>(x + area->w + 1, MapSizeX());
4116 	int x1 = std::max<int>(x - 1, 0);
4117 
4118 	int y2 = std::min<int>(y + area->h + 1, MapSizeY());
4119 	int y1 = std::max<int>(y - 1, 0);
4120 
4121 	TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4122 	for (TileIndex tile : ta) {
4123 		if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4124 	}
4125 }
4126 
BuildOilRig(TileIndex tile)4127 void BuildOilRig(TileIndex tile)
4128 {
4129 	if (!Station::CanAllocateItem()) {
4130 		Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4131 		return;
4132 	}
4133 
4134 	Station *st = new Station(tile);
4135 	_station_kdtree.Insert(st->index);
4136 	st->town = ClosestTownFromTile(tile, UINT_MAX);
4137 
4138 	st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4139 
4140 	assert(IsTileType(tile, MP_INDUSTRY));
4141 	/* Mark industry as associated both ways */
4142 	st->industry = Industry::GetByTile(tile);
4143 	st->industry->neutral_station = st;
4144 	DeleteAnimatedTile(tile);
4145 	MakeOilrig(tile, st->index, GetWaterClass(tile));
4146 
4147 	st->owner = OWNER_NONE;
4148 	st->airport.type = AT_OILRIG;
4149 	st->airport.Add(tile);
4150 	st->ship_station.Add(tile);
4151 	st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4152 	st->build_date = _date;
4153 	UpdateStationDockingTiles(st);
4154 
4155 	st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4156 
4157 	st->UpdateVirtCoord();
4158 	st->RecomputeCatchment();
4159 	UpdateStationAcceptance(st, false);
4160 }
4161 
DeleteOilRig(TileIndex tile)4162 void DeleteOilRig(TileIndex tile)
4163 {
4164 	Station *st = Station::GetByTile(tile);
4165 
4166 	MakeWaterKeepingClass(tile, OWNER_NONE);
4167 
4168 	/* The oil rig station is not supposed to be shared with anything else */
4169 	assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4170 	if (st->industry != nullptr && st->industry->neutral_station == st) {
4171 		/* Don't leave dangling neutral station pointer */
4172 		st->industry->neutral_station = nullptr;
4173 	}
4174 	delete st;
4175 }
4176 
ChangeTileOwner_Station(TileIndex tile,Owner old_owner,Owner new_owner)4177 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4178 {
4179 	if (IsRoadStopTile(tile)) {
4180 		for (RoadTramType rtt : _roadtramtypes) {
4181 			/* Update all roadtypes, no matter if they are present */
4182 			if (GetRoadOwner(tile, rtt) == old_owner) {
4183 				RoadType rt = GetRoadType(tile, rtt);
4184 				if (rt != INVALID_ROADTYPE) {
4185 					/* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4186 					Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4187 					if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4188 				}
4189 				SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4190 			}
4191 		}
4192 	}
4193 
4194 	if (!IsTileOwner(tile, old_owner)) return;
4195 
4196 	if (new_owner != INVALID_OWNER) {
4197 		/* Update company infrastructure counts. Only do it here
4198 		 * if the new owner is valid as otherwise the clear
4199 		 * command will do it for us. No need to dirty windows
4200 		 * here, we'll redraw the whole screen anyway.*/
4201 		Company *old_company = Company::Get(old_owner);
4202 		Company *new_company = Company::Get(new_owner);
4203 
4204 		/* Update counts for underlying infrastructure. */
4205 		switch (GetStationType(tile)) {
4206 			case STATION_RAIL:
4207 			case STATION_WAYPOINT:
4208 				if (!IsStationTileBlocked(tile)) {
4209 					old_company->infrastructure.rail[GetRailType(tile)]--;
4210 					new_company->infrastructure.rail[GetRailType(tile)]++;
4211 				}
4212 				break;
4213 
4214 			case STATION_BUS:
4215 			case STATION_TRUCK:
4216 				/* Road stops were already handled above. */
4217 				break;
4218 
4219 			case STATION_BUOY:
4220 			case STATION_DOCK:
4221 				if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4222 					old_company->infrastructure.water--;
4223 					new_company->infrastructure.water++;
4224 				}
4225 				break;
4226 
4227 			default:
4228 				break;
4229 		}
4230 
4231 		/* Update station tile count. */
4232 		if (!IsBuoy(tile) && !IsAirport(tile)) {
4233 			old_company->infrastructure.station--;
4234 			new_company->infrastructure.station++;
4235 		}
4236 
4237 		/* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4238 		SetTileOwner(tile, new_owner);
4239 		InvalidateWindowClassesData(WC_STATION_LIST, 0);
4240 	} else {
4241 		if (IsDriveThroughStopTile(tile)) {
4242 			/* Remove the drive-through road stop */
4243 			DoCommand(tile, 1 | 1 << 8, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, DC_EXEC | DC_BANKRUPT, CMD_REMOVE_ROAD_STOP);
4244 			assert(IsTileType(tile, MP_ROAD));
4245 			/* Change owner of tile and all roadtypes */
4246 			ChangeTileOwner(tile, old_owner, new_owner);
4247 		} else {
4248 			DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
4249 			/* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4250 			 * Update owner of buoy if it was not removed (was in orders).
4251 			 * Do not update when owned by OWNER_WATER (sea and rivers). */
4252 			if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4253 		}
4254 	}
4255 }
4256 
4257 /**
4258  * Check if a drive-through road stop tile can be cleared.
4259  * Road stops built on town-owned roads check the conditions
4260  * that would allow clearing of the original road.
4261  * @param tile road stop tile to check
4262  * @param flags command flags
4263  * @return true if the road can be cleared
4264  */
CanRemoveRoadWithStop(TileIndex tile,DoCommandFlag flags)4265 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4266 {
4267 	/* Yeah... water can always remove stops, right? */
4268 	if (_current_company == OWNER_WATER) return true;
4269 
4270 	if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4271 		Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4272 		if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4273 	}
4274 	if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4275 		Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4276 		if (road_owner != OWNER_TOWN) {
4277 			if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4278 		} else {
4279 			if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags).Failed()) return false;
4280 		}
4281 	}
4282 
4283 	return true;
4284 }
4285 
4286 /**
4287  * Clear a single tile of a station.
4288  * @param tile The tile to clear.
4289  * @param flags The DoCommand flags related to the "command".
4290  * @return The cost, or error of clearing.
4291  */
ClearTile_Station(TileIndex tile,DoCommandFlag flags)4292 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4293 {
4294 	if (flags & DC_AUTO) {
4295 		switch (GetStationType(tile)) {
4296 			default: break;
4297 			case STATION_RAIL:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4298 			case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4299 			case STATION_AIRPORT:  return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4300 			case STATION_TRUCK:    return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4301 			case STATION_BUS:      return_cmd_error(HasTileRoadType(tile, RTT_TRAM) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4302 			case STATION_BUOY:     return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4303 			case STATION_DOCK:     return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4304 			case STATION_OILRIG:
4305 				SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4306 				return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4307 		}
4308 	}
4309 
4310 	switch (GetStationType(tile)) {
4311 		case STATION_RAIL:     return RemoveRailStation(tile, flags);
4312 		case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4313 		case STATION_AIRPORT:  return RemoveAirport(tile, flags);
4314 		case STATION_TRUCK:
4315 			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4316 				return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4317 			}
4318 			return RemoveRoadStop(tile, flags);
4319 		case STATION_BUS:
4320 			if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4321 				return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4322 			}
4323 			return RemoveRoadStop(tile, flags);
4324 		case STATION_BUOY:     return RemoveBuoy(tile, flags);
4325 		case STATION_DOCK:     return RemoveDock(tile, flags);
4326 		default: break;
4327 	}
4328 
4329 	return CMD_ERROR;
4330 }
4331 
TerraformTile_Station(TileIndex tile,DoCommandFlag flags,int z_new,Slope tileh_new)4332 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4333 {
4334 	if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4335 		/* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4336 		 *       TTDP does not call it.
4337 		 */
4338 		if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4339 			switch (GetStationType(tile)) {
4340 				case STATION_WAYPOINT:
4341 				case STATION_RAIL: {
4342 					DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4343 					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4344 					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4345 					return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4346 				}
4347 
4348 				case STATION_AIRPORT:
4349 					return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4350 
4351 				case STATION_TRUCK:
4352 				case STATION_BUS: {
4353 					DiagDirection direction = GetRoadStopDir(tile);
4354 					if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4355 					if (IsDriveThroughStopTile(tile)) {
4356 						if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4357 					}
4358 					return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4359 				}
4360 
4361 				default: break;
4362 			}
4363 		}
4364 	}
4365 	return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
4366 }
4367 
4368 /**
4369  * Get flow for a station.
4370  * @param st Station to get flow for.
4371  * @return Flow for st.
4372  */
GetShare(StationID st) const4373 uint FlowStat::GetShare(StationID st) const
4374 {
4375 	uint32 prev = 0;
4376 	for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4377 		if (it->second == st) {
4378 			return it->first - prev;
4379 		} else {
4380 			prev = it->first;
4381 		}
4382 	}
4383 	return 0;
4384 }
4385 
4386 /**
4387  * Get a station a package can be routed to, but exclude the given ones.
4388  * @param excluded StationID not to be selected.
4389  * @param excluded2 Another StationID not to be selected.
4390  * @return A station ID from the shares map.
4391  */
GetVia(StationID excluded,StationID excluded2) const4392 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4393 {
4394 	if (this->unrestricted == 0) return INVALID_STATION;
4395 	assert(!this->shares.empty());
4396 	SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4397 	assert(it != this->shares.end() && it->first <= this->unrestricted);
4398 	if (it->second != excluded && it->second != excluded2) return it->second;
4399 
4400 	/* We've hit one of the excluded stations.
4401 	 * Draw another share, from outside its range. */
4402 
4403 	uint end = it->first;
4404 	uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4405 	uint interval = end - begin;
4406 	if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4407 	uint new_max = this->unrestricted - interval;
4408 	uint rand = RandomRange(new_max);
4409 	SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4410 			this->shares.upper_bound(rand + interval);
4411 	assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4412 	if (it2->second != excluded && it2->second != excluded2) return it2->second;
4413 
4414 	/* We've hit the second excluded station.
4415 	 * Same as before, only a bit more complicated. */
4416 
4417 	uint end2 = it2->first;
4418 	uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4419 	uint interval2 = end2 - begin2;
4420 	if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4421 	new_max -= interval2;
4422 	if (begin > begin2) {
4423 		Swap(begin, begin2);
4424 		Swap(end, end2);
4425 		Swap(interval, interval2);
4426 	}
4427 	rand = RandomRange(new_max);
4428 	SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4429 	if (rand < begin) {
4430 		it3 = this->shares.upper_bound(rand);
4431 	} else if (rand < begin2 - interval) {
4432 		it3 = this->shares.upper_bound(rand + interval);
4433 	} else {
4434 		it3 = this->shares.upper_bound(rand + interval + interval2);
4435 	}
4436 	assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4437 	return it3->second;
4438 }
4439 
4440 /**
4441  * Reduce all flows to minimum capacity so that they don't get in the way of
4442  * link usage statistics too much. Keep them around, though, to continue
4443  * routing any remaining cargo.
4444  */
Invalidate()4445 void FlowStat::Invalidate()
4446 {
4447 	assert(!this->shares.empty());
4448 	SharesMap new_shares;
4449 	uint i = 0;
4450 	for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4451 		new_shares[++i] = it->second;
4452 		if (it->first == this->unrestricted) this->unrestricted = i;
4453 	}
4454 	this->shares.swap(new_shares);
4455 	assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4456 }
4457 
4458 /**
4459  * Change share for specified station. By specifying INT_MIN as parameter you
4460  * can erase a share. Newly added flows will be unrestricted.
4461  * @param st Next Hop to be removed.
4462  * @param flow Share to be added or removed.
4463  */
ChangeShare(StationID st,int flow)4464 void FlowStat::ChangeShare(StationID st, int flow)
4465 {
4466 	/* We assert only before changing as afterwards the shares can actually
4467 	 * be empty. In that case the whole flow stat must be deleted then. */
4468 	assert(!this->shares.empty());
4469 
4470 	uint removed_shares = 0;
4471 	uint added_shares = 0;
4472 	uint last_share = 0;
4473 	SharesMap new_shares;
4474 	for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4475 		if (it->second == st) {
4476 			if (flow < 0) {
4477 				uint share = it->first - last_share;
4478 				if (flow == INT_MIN || (uint)(-flow) >= share) {
4479 					removed_shares += share;
4480 					if (it->first <= this->unrestricted) this->unrestricted -= share;
4481 					if (flow != INT_MIN) flow += share;
4482 					last_share = it->first;
4483 					continue; // remove the whole share
4484 				}
4485 				removed_shares += (uint)(-flow);
4486 			} else {
4487 				added_shares += (uint)(flow);
4488 			}
4489 			if (it->first <= this->unrestricted) this->unrestricted += flow;
4490 
4491 			/* If we don't continue above the whole flow has been added or
4492 			 * removed. */
4493 			flow = 0;
4494 		}
4495 		new_shares[it->first + added_shares - removed_shares] = it->second;
4496 		last_share = it->first;
4497 	}
4498 	if (flow > 0) {
4499 		new_shares[last_share + (uint)flow] = st;
4500 		if (this->unrestricted < last_share) {
4501 			this->ReleaseShare(st);
4502 		} else {
4503 			this->unrestricted += flow;
4504 		}
4505 	}
4506 	this->shares.swap(new_shares);
4507 }
4508 
4509 /**
4510  * Restrict a flow by moving it to the end of the map and decreasing the amount
4511  * of unrestricted flow.
4512  * @param st Station of flow to be restricted.
4513  */
RestrictShare(StationID st)4514 void FlowStat::RestrictShare(StationID st)
4515 {
4516 	assert(!this->shares.empty());
4517 	uint flow = 0;
4518 	uint last_share = 0;
4519 	SharesMap new_shares;
4520 	for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4521 		if (flow == 0) {
4522 			if (it->first > this->unrestricted) return; // Not present or already restricted.
4523 			if (it->second == st) {
4524 				flow = it->first - last_share;
4525 				this->unrestricted -= flow;
4526 			} else {
4527 				new_shares[it->first] = it->second;
4528 			}
4529 		} else {
4530 			new_shares[it->first - flow] = it->second;
4531 		}
4532 		last_share = it->first;
4533 	}
4534 	if (flow == 0) return;
4535 	new_shares[last_share + flow] = st;
4536 	this->shares.swap(new_shares);
4537 	assert(!this->shares.empty());
4538 }
4539 
4540 /**
4541  * Release ("unrestrict") a flow by moving it to the begin of the map and
4542  * increasing the amount of unrestricted flow.
4543  * @param st Station of flow to be released.
4544  */
ReleaseShare(StationID st)4545 void FlowStat::ReleaseShare(StationID st)
4546 {
4547 	assert(!this->shares.empty());
4548 	uint flow = 0;
4549 	uint next_share = 0;
4550 	bool found = false;
4551 	for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4552 		if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4553 		if (found) {
4554 			flow = next_share - it->first;
4555 			this->unrestricted += flow;
4556 			break;
4557 		} else {
4558 			if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4559 			if (it->second == st) found = true;
4560 		}
4561 		next_share = it->first;
4562 	}
4563 	if (flow == 0) return;
4564 	SharesMap new_shares;
4565 	new_shares[flow] = st;
4566 	for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4567 		if (it->second != st) {
4568 			new_shares[flow + it->first] = it->second;
4569 		} else {
4570 			flow = 0;
4571 		}
4572 	}
4573 	this->shares.swap(new_shares);
4574 	assert(!this->shares.empty());
4575 }
4576 
4577 /**
4578  * Scale all shares from link graph's runtime to monthly values.
4579  * @param runtime Time the link graph has been running without compression.
4580  * @pre runtime must be greater than 0 as we don't want infinite flow values.
4581  */
ScaleToMonthly(uint runtime)4582 void FlowStat::ScaleToMonthly(uint runtime)
4583 {
4584 	assert(runtime > 0);
4585 	SharesMap new_shares;
4586 	uint share = 0;
4587 	for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4588 		share = std::max(share + 1, i->first * 30 / runtime);
4589 		new_shares[share] = i->second;
4590 		if (this->unrestricted == i->first) this->unrestricted = share;
4591 	}
4592 	this->shares.swap(new_shares);
4593 }
4594 
4595 /**
4596  * Add some flow from "origin", going via "via".
4597  * @param origin Origin of the flow.
4598  * @param via Next hop.
4599  * @param flow Amount of flow to be added.
4600  */
AddFlow(StationID origin,StationID via,uint flow)4601 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4602 {
4603 	FlowStatMap::iterator origin_it = this->find(origin);
4604 	if (origin_it == this->end()) {
4605 		this->insert(std::make_pair(origin, FlowStat(via, flow)));
4606 	} else {
4607 		origin_it->second.ChangeShare(via, flow);
4608 		assert(!origin_it->second.GetShares()->empty());
4609 	}
4610 }
4611 
4612 /**
4613  * Pass on some flow, remembering it as invalid, for later subtraction from
4614  * locally consumed flow. This is necessary because we can't have negative
4615  * flows and we don't want to sort the flows before adding them up.
4616  * @param origin Origin of the flow.
4617  * @param via Next hop.
4618  * @param flow Amount of flow to be passed.
4619  */
PassOnFlow(StationID origin,StationID via,uint flow)4620 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4621 {
4622 	FlowStatMap::iterator prev_it = this->find(origin);
4623 	if (prev_it == this->end()) {
4624 		FlowStat fs(via, flow);
4625 		fs.AppendShare(INVALID_STATION, flow);
4626 		this->insert(std::make_pair(origin, fs));
4627 	} else {
4628 		prev_it->second.ChangeShare(via, flow);
4629 		prev_it->second.ChangeShare(INVALID_STATION, flow);
4630 		assert(!prev_it->second.GetShares()->empty());
4631 	}
4632 }
4633 
4634 /**
4635  * Subtract invalid flows from locally consumed flow.
4636  * @param self ID of own station.
4637  */
FinalizeLocalConsumption(StationID self)4638 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4639 {
4640 	for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4641 		FlowStat &fs = i->second;
4642 		uint local = fs.GetShare(INVALID_STATION);
4643 		if (local > INT_MAX) { // make sure it fits in an int
4644 			fs.ChangeShare(self, -INT_MAX);
4645 			fs.ChangeShare(INVALID_STATION, -INT_MAX);
4646 			local -= INT_MAX;
4647 		}
4648 		fs.ChangeShare(self, -(int)local);
4649 		fs.ChangeShare(INVALID_STATION, -(int)local);
4650 
4651 		/* If the local share is used up there must be a share for some
4652 		 * remote station. */
4653 		assert(!fs.GetShares()->empty());
4654 	}
4655 }
4656 
4657 /**
4658  * Delete all flows at a station for specific cargo and destination.
4659  * @param via Remote station of flows to be deleted.
4660  * @return IDs of source stations for which the complete FlowStat, not only a
4661  *         share, has been erased.
4662  */
DeleteFlows(StationID via)4663 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4664 {
4665 	StationIDStack ret;
4666 	for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4667 		FlowStat &s_flows = f_it->second;
4668 		s_flows.ChangeShare(via, INT_MIN);
4669 		if (s_flows.GetShares()->empty()) {
4670 			ret.Push(f_it->first);
4671 			this->erase(f_it++);
4672 		} else {
4673 			++f_it;
4674 		}
4675 	}
4676 	return ret;
4677 }
4678 
4679 /**
4680  * Restrict all flows at a station for specific cargo and destination.
4681  * @param via Remote station of flows to be restricted.
4682  */
RestrictFlows(StationID via)4683 void FlowStatMap::RestrictFlows(StationID via)
4684 {
4685 	for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4686 		it->second.RestrictShare(via);
4687 	}
4688 }
4689 
4690 /**
4691  * Release all flows at a station for specific cargo and destination.
4692  * @param via Remote station of flows to be released.
4693  */
ReleaseFlows(StationID via)4694 void FlowStatMap::ReleaseFlows(StationID via)
4695 {
4696 	for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4697 		it->second.ReleaseShare(via);
4698 	}
4699 }
4700 
4701 /**
4702  * Get the sum of all flows from this FlowStatMap.
4703  * @return sum of all flows.
4704  */
GetFlow() const4705 uint FlowStatMap::GetFlow() const
4706 {
4707 	uint ret = 0;
4708 	for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4709 		ret += (--(i->second.GetShares()->end()))->first;
4710 	}
4711 	return ret;
4712 }
4713 
4714 /**
4715  * Get the sum of flows via a specific station from this FlowStatMap.
4716  * @param via Remote station to look for.
4717  * @return all flows for 'via' added up.
4718  */
GetFlowVia(StationID via) const4719 uint FlowStatMap::GetFlowVia(StationID via) const
4720 {
4721 	uint ret = 0;
4722 	for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4723 		ret += i->second.GetShare(via);
4724 	}
4725 	return ret;
4726 }
4727 
4728 /**
4729  * Get the sum of flows from a specific station from this FlowStatMap.
4730  * @param from Origin station to look for.
4731  * @return all flows from 'from' added up.
4732  */
GetFlowFrom(StationID from) const4733 uint FlowStatMap::GetFlowFrom(StationID from) const
4734 {
4735 	FlowStatMap::const_iterator i = this->find(from);
4736 	if (i == this->end()) return 0;
4737 	return (--(i->second.GetShares()->end()))->first;
4738 }
4739 
4740 /**
4741  * Get the flow from a specific station via a specific other station.
4742  * @param from Origin station to look for.
4743  * @param via Remote station to look for.
4744  * @return flow share originating at 'from' and going to 'via'.
4745  */
GetFlowFromVia(StationID from,StationID via) const4746 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4747 {
4748 	FlowStatMap::const_iterator i = this->find(from);
4749 	if (i == this->end()) return 0;
4750 	return i->second.GetShare(via);
4751 }
4752 
4753 extern const TileTypeProcs _tile_type_station_procs = {
4754 	DrawTile_Station,           // draw_tile_proc
4755 	GetSlopePixelZ_Station,     // get_slope_z_proc
4756 	ClearTile_Station,          // clear_tile_proc
4757 	nullptr,                       // add_accepted_cargo_proc
4758 	GetTileDesc_Station,        // get_tile_desc_proc
4759 	GetTileTrackStatus_Station, // get_tile_track_status_proc
4760 	ClickTile_Station,          // click_tile_proc
4761 	AnimateTile_Station,        // animate_tile_proc
4762 	TileLoop_Station,           // tile_loop_proc
4763 	ChangeTileOwner_Station,    // change_tile_owner_proc
4764 	nullptr,                       // add_produced_cargo_proc
4765 	VehicleEnter_Station,       // vehicle_enter_tile_proc
4766 	GetFoundation_Station,      // get_foundation_proc
4767 	TerraformTile_Station,      // terraform_tile_proc
4768 };
4769