Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / station_cmd.cpp
blobef8e6bc7e28148aa66e19fb70cc5b620703fcc49
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 */
8 /** @file station_cmd.cpp Handling of station tiles. */
10 #include "stdafx.h"
11 #include "aircraft.h"
12 #include "bridge_map.h"
13 #include "viewport_func.h"
14 #include "viewport_kdtree.h"
15 #include "command_func.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "train.h"
19 #include "ship.h"
20 #include "roadveh.h"
21 #include "industry.h"
22 #include "newgrf_cargo.h"
23 #include "newgrf_debug.h"
24 #include "newgrf_station.h"
25 #include "newgrf_canal.h" /* For the buoy */
26 #include "pathfinder/yapf/yapf_cache.h"
27 #include "road_internal.h" /* For drawing catenary/checking road removal */
28 #include "autoslope.h"
29 #include "water.h"
30 #include "strings_internal.h"
31 #include "clear_func.h"
32 #include "timer/timer_game_calendar.h"
33 #include "vehicle_func.h"
34 #include "string_func.h"
35 #include "animated_tile_func.h"
36 #include "elrail_func.h"
37 #include "station_base.h"
38 #include "station_func.h"
39 #include "station_kdtree.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "newgrf_roadtype.h"
43 #include "waypoint_base.h"
44 #include "waypoint_func.h"
45 #include "pbs.h"
46 #include "debug.h"
47 #include "core/random_func.hpp"
48 #include "core/container_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 #include "station_cmd.h"
60 #include "waypoint_cmd.h"
61 #include "landscape_cmd.h"
62 #include "rail_cmd.h"
63 #include "newgrf_roadstop.h"
64 #include "timer/timer.h"
65 #include "timer/timer_game_calendar.h"
66 #include "timer/timer_game_economy.h"
67 #include "timer/timer_game_tick.h"
68 #include "cheat_type.h"
70 #include "table/strings.h"
72 #include <bitset>
74 #include "safeguards.h"
76 /**
77 * Static instance of FlowStat::SharesMap.
78 * Note: This instance is created on task start.
79 * Lazy creation on first usage results in a data race between the CDist threads.
81 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
83 /**
84 * Check whether the given tile is a hangar.
85 * @param t the tile to of whether it is a hangar.
86 * @pre IsTileType(t, MP_STATION)
87 * @return true if and only if the tile is a hangar.
89 bool IsHangar(Tile t)
91 assert(IsTileType(t, MP_STATION));
93 /* If the tile isn't an airport there's no chance it's a hangar. */
94 if (!IsAirport(t)) return false;
96 const Station *st = Station::GetByTile(t);
97 const AirportSpec *as = st->airport.GetSpec();
99 for (uint i = 0; i < as->nof_depots; i++) {
100 if (st->airport.GetHangarTile(i) == TileIndex(t)) return true;
103 return false;
107 * Look for a station owned by the given company around the given tile area.
108 * @param ta the area to search over
109 * @param closest_station the closest owned station found so far
110 * @param company the company whose stations to look for
111 * @param st to 'return' the found station
112 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
114 template <class T>
115 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
117 ta.Expand(1);
119 /* check around to see if there are any stations there owned by the company */
120 for (TileIndex tile_cur : ta) {
121 if (IsTileType(tile_cur, MP_STATION)) {
122 StationID t = GetStationIndex(tile_cur);
123 if (!T::IsValidID(t) || Station::Get(t)->owner != company) continue;
124 if (closest_station == INVALID_STATION) {
125 closest_station = t;
126 } else if (closest_station != t) {
127 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
131 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
132 return CommandCost();
136 * Function to check whether the given tile matches some criterion.
137 * @param tile the tile to check
138 * @return true if it matches, false otherwise
140 typedef bool (*CMSAMatcher)(TileIndex tile);
143 * Counts the numbers of tiles matching a specific type in the area around
144 * @param tile the center tile of the 'count area'
145 * @param cmp the comparator/matcher (@see CMSAMatcher)
146 * @return the number of matching tiles around
148 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
150 int num = 0;
152 for (int dx = -3; dx <= 3; dx++) {
153 for (int dy = -3; dy <= 3; dy++) {
154 TileIndex t = TileAddWrap(tile, dx, dy);
155 if (t != INVALID_TILE && cmp(t)) num++;
159 return num;
163 * Check whether the tile is a mine.
164 * @param tile the tile to investigate.
165 * @return true if and only if the tile is a mine
167 static bool CMSAMine(TileIndex tile)
169 /* No industry */
170 if (!IsTileType(tile, MP_INDUSTRY)) return false;
172 const Industry *ind = Industry::GetByTile(tile);
174 /* No extractive industry */
175 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
177 for (const auto &p : ind->produced) {
178 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
179 * Also the production of passengers and mail is ignored. */
180 if (IsValidCargoID(p.cargo) &&
181 (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
182 return true;
186 return false;
190 * Check whether the tile is water.
191 * @param tile the tile to investigate.
192 * @return true if and only if the tile is a water tile
194 static bool CMSAWater(TileIndex tile)
196 return IsTileType(tile, MP_WATER) && IsWater(tile);
200 * Check whether the tile is a tree.
201 * @param tile the tile to investigate.
202 * @return true if and only if the tile is a tree tile
204 static bool CMSATree(TileIndex tile)
206 return IsTileType(tile, MP_TREES);
209 #define M(x) ((x) - STR_SV_STNAME)
211 enum StationNaming {
212 STATIONNAMING_RAIL,
213 STATIONNAMING_ROAD,
214 STATIONNAMING_AIRPORT,
215 STATIONNAMING_OILRIG,
216 STATIONNAMING_DOCK,
217 STATIONNAMING_HELIPORT,
220 /** Information to handle station action 0 property 24 correctly */
221 struct StationNameInformation {
222 uint32_t free_names; ///< Current bitset of free names (we can remove names).
223 std::bitset<NUM_INDUSTRYTYPES> indtypes; ///< Bit set indicating when an industry type has been found.
227 * Find a station action 0 property 24 station name, or reduce the
228 * free_names if needed.
229 * @param tile the tile to search
230 * @param user_data the StationNameInformation to base the search on
231 * @return true if the tile contains an industry that has not given
232 * its name to one of the other stations in town.
234 static bool FindNearIndustryName(TileIndex tile, void *user_data)
236 /* All already found industry types */
237 StationNameInformation *sni = (StationNameInformation*)user_data;
238 if (!IsTileType(tile, MP_INDUSTRY)) return false;
240 /* If the station name is undefined it means that it doesn't name a station */
241 IndustryType indtype = GetIndustryType(tile);
242 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
244 /* In all cases if an industry that provides a name is found two of
245 * the standard names will be disabled. */
246 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
247 return !sni->indtypes[indtype];
250 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
252 static const uint32_t _gen_station_name_bits[] = {
253 0, // STATIONNAMING_RAIL
254 0, // STATIONNAMING_ROAD
255 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
256 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
257 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
258 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
261 const Town *t = st->town;
263 StationNameInformation sni{};
264 sni.free_names = UINT32_MAX;
266 for (const Station *s : Station::Iterate()) {
267 if (s != st && s->town == t) {
268 if (s->indtype != IT_INVALID) {
269 sni.indtypes[s->indtype] = true;
270 StringID name = GetIndustrySpec(s->indtype)->station_name;
271 if (name != STR_UNDEFINED) {
272 /* Filter for other industrytypes with the same name */
273 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
274 const IndustrySpec *indsp = GetIndustrySpec(it);
275 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
278 continue;
280 uint str = M(s->string_id);
281 if (str <= 0x20) {
282 if (str == M(STR_SV_STNAME_FOREST)) {
283 str = M(STR_SV_STNAME_WOODS);
285 ClrBit(sni.free_names, str);
290 TileIndex indtile = tile;
291 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
292 /* An industry has been found nearby */
293 IndustryType indtype = GetIndustryType(indtile);
294 const IndustrySpec *indsp = GetIndustrySpec(indtype);
295 /* STR_NULL means it only disables oil rig/mines */
296 if (indsp->station_name != STR_NULL) {
297 st->indtype = indtype;
298 return STR_SV_STNAME_FALLBACK;
302 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
304 /* check default names */
305 uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
306 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
308 /* check mine? */
309 if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
310 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
311 return STR_SV_STNAME_MINES;
315 /* check close enough to town to get central as name? */
316 if (DistanceMax(tile, t->xy) < 8) {
317 if (HasBit(sni.free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
319 if (HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
322 /* Check lakeside */
323 if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
324 DistanceFromEdge(tile) < 20 &&
325 CountMapSquareAround(tile, CMSAWater) >= 5) {
326 return STR_SV_STNAME_LAKESIDE;
329 /* Check woods */
330 if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
331 CountMapSquareAround(tile, CMSATree) >= 8 ||
332 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
334 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
337 /* check elevation compared to town */
338 int z = GetTileZ(tile);
339 int z2 = GetTileZ(t->xy);
340 if (z < z2) {
341 if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
342 } else if (z > z2) {
343 if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
346 /* check direction compared to town */
347 static const int8_t _direction_and_table[] = {
348 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
349 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
350 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
351 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
354 sni.free_names &= _direction_and_table[
355 (TileX(tile) < TileX(t->xy)) +
356 (TileY(tile) < TileY(t->xy)) * 2];
358 /** Bitmask of remaining station names that can be used when a more specific name has not been used. */
359 static const uint32_t fallback_names = (
360 (1U << M(STR_SV_STNAME_NORTH)) |
361 (1U << M(STR_SV_STNAME_SOUTH)) |
362 (1U << M(STR_SV_STNAME_EAST)) |
363 (1U << M(STR_SV_STNAME_WEST)) |
364 (1U << M(STR_SV_STNAME_TRANSFER)) |
365 (1U << M(STR_SV_STNAME_HALT)) |
366 (1U << M(STR_SV_STNAME_EXCHANGE)) |
367 (1U << M(STR_SV_STNAME_ANNEXE)) |
368 (1U << M(STR_SV_STNAME_SIDINGS)) |
369 (1U << M(STR_SV_STNAME_BRANCH)) |
370 (1U << M(STR_SV_STNAME_UPPER)) |
371 (1U << M(STR_SV_STNAME_LOWER))
374 sni.free_names &= fallback_names;
375 return (sni.free_names == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(sni.free_names));
377 #undef M
380 * Find the closest deleted station of the current company
381 * @param tile the tile to search from.
382 * @return the closest station or nullptr if too far.
384 static Station *GetClosestDeletedStation(TileIndex tile)
386 uint threshold = 8;
388 Station *best_station = nullptr;
389 ForAllStationsRadius(tile, threshold, [&](Station *st) {
390 if (!st->IsInUse() && st->owner == _current_company) {
391 uint cur_dist = DistanceManhattan(tile, st->xy);
393 if (cur_dist < threshold) {
394 threshold = cur_dist;
395 best_station = st;
396 } else if (cur_dist == threshold && best_station != nullptr) {
397 /* In case of a tie, lowest station ID wins */
398 if (st->index < best_station->index) best_station = st;
403 return best_station;
407 void Station::GetTileArea(TileArea *ta, StationType type) const
409 switch (type) {
410 case STATION_RAIL:
411 *ta = this->train_station;
412 return;
414 case STATION_AIRPORT:
415 *ta = this->airport;
416 return;
418 case STATION_TRUCK:
419 *ta = this->truck_station;
420 return;
422 case STATION_BUS:
423 *ta = this->bus_station;
424 return;
426 case STATION_DOCK:
427 case STATION_OILRIG:
428 *ta = this->docking_station;
429 return;
431 default: NOT_REACHED();
436 * Update the virtual coords needed to draw the station sign.
438 void Station::UpdateVirtCoord()
440 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
442 pt.y -= 32 * ZOOM_LVL_BASE;
443 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
445 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
447 SetDParam(0, this->index);
448 SetDParam(1, this->facilities);
449 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
451 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
453 SetWindowDirty(WC_STATION_VIEW, this->index);
457 * Move the station main coordinate somewhere else.
458 * @param new_xy new tile location of the sign
460 void Station::MoveSign(TileIndex new_xy)
462 if (this->xy == new_xy) return;
464 _station_kdtree.Remove(this->index);
466 this->BaseStation::MoveSign(new_xy);
468 _station_kdtree.Insert(this->index);
471 /** Update the virtual coords needed to draw the station sign for all stations. */
472 void UpdateAllStationVirtCoords()
474 for (BaseStation *st : BaseStation::Iterate()) {
475 st->UpdateVirtCoord();
479 void BaseStation::FillCachedName() const
481 auto tmp_params = MakeParameters(this->index);
482 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
485 void ClearAllStationCachedNames()
487 for (BaseStation *st : BaseStation::Iterate()) {
488 st->cached_name.clear();
493 * Get a mask of the cargo types that the station accepts.
494 * @param st Station to query
495 * @return the expected mask
497 CargoTypes GetAcceptanceMask(const Station *st)
499 CargoTypes mask = 0;
501 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
502 if (HasBit(it->status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, std::distance(std::begin(st->goods), it));
504 return mask;
508 * Get a mask of the cargo types that are empty at the station.
509 * @param st Station to query
510 * @return the empty mask
512 CargoTypes GetEmptyMask(const Station *st)
514 CargoTypes mask = 0;
516 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
517 if (it->cargo.TotalCount() == 0) SetBit(mask, std::distance(std::begin(st->goods), it));
519 return mask;
523 * Add news item for when a station changes which cargoes it accepts.
524 * @param st Station of cargo change.
525 * @param cargoes Bit mask of cargo types to list.
526 * @param reject True iff the station rejects the cargo types.
528 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
530 SetDParam(0, st->index);
531 SetDParam(1, cargoes);
532 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
533 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
537 * Get the cargo types being produced around the tile (in a rectangle).
538 * @param north_tile Northern most tile of area
539 * @param w X extent of the area
540 * @param h Y extent of the area
541 * @param rad Search radius in addition to the given area
543 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
545 CargoArray produced{};
546 std::set<IndustryID> industries;
547 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
549 /* Loop over all tiles to get the produced cargo of
550 * everything except industries */
551 for (TileIndex tile : ta) {
552 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
553 AddProducedCargo(tile, produced);
556 /* Loop over the seen industries. They produce cargo for
557 * anything that is within 'rad' of any one of their tiles.
559 for (IndustryID industry : industries) {
560 const Industry *i = Industry::Get(industry);
561 /* Skip industry with neutral station */
562 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
564 for (const auto &p : i->produced) {
565 if (IsValidCargoID(p.cargo)) produced[p.cargo]++;
569 return produced;
573 * Get the acceptance of cargoes around the tile in 1/8.
574 * @param center_tile Center of the search area
575 * @param w X extent of area
576 * @param h Y extent of area
577 * @param rad Search radius in addition to given area
578 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
579 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
581 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
583 CargoArray acceptance{};
584 if (always_accepted != nullptr) *always_accepted = 0;
586 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
588 for (TileIndex tile : ta) {
589 /* Ignore industry if it has a neutral station. */
590 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
592 AddAcceptedCargo(tile, acceptance, always_accepted);
595 return acceptance;
599 * Get the acceptance of cargoes around the station in.
600 * @param st Station to get acceptance of.
601 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
603 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
605 CargoArray acceptance{};
606 if (always_accepted != nullptr) *always_accepted = 0;
608 BitmapTileIterator it(st->catchment_tiles);
609 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
610 AddAcceptedCargo(tile, acceptance, always_accepted);
613 return acceptance;
617 * Update the acceptance for a station.
618 * @param st Station to update
619 * @param show_msg controls whether to display a message that acceptance was changed.
621 void UpdateStationAcceptance(Station *st, bool show_msg)
623 /* old accepted goods types */
624 CargoTypes old_acc = GetAcceptanceMask(st);
626 /* And retrieve the acceptance. */
627 CargoArray acceptance{};
628 if (!st->rect.IsEmpty()) {
629 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
632 /* Adjust in case our station only accepts fewer kinds of goods */
633 for (CargoID i = 0; i < NUM_CARGO; i++) {
634 uint amt = acceptance[i];
636 /* Make sure the station can accept the goods type. */
637 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
638 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
639 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
640 amt = 0;
643 GoodsEntry &ge = st->goods[i];
644 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
645 if (LinkGraph::IsValidID(ge.link_graph)) {
646 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
650 /* Only show a message in case the acceptance was actually changed. */
651 CargoTypes new_acc = GetAcceptanceMask(st);
652 if (old_acc == new_acc) return;
654 /* show a message to report that the acceptance was changed? */
655 if (show_msg && st->owner == _local_company && st->IsInUse()) {
656 /* Combine old and new masks to get changes */
657 CargoTypes accepts = new_acc & ~old_acc;
658 CargoTypes rejects = ~new_acc & old_acc;
660 /* Show news message if there are any changes */
661 if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
662 if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
665 /* redraw the station view since acceptance changed */
666 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
669 static void UpdateStationSignCoord(BaseStation *st)
671 const StationRect *r = &st->rect;
673 if (r->IsEmpty()) return; // no tiles belong to this station
675 /* clamp sign coord to be inside the station rect */
676 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
677 st->MoveSign(new_xy);
679 if (!Station::IsExpected(st)) return;
680 Station *full_station = Station::From(st);
681 for (const GoodsEntry &ge : full_station->goods) {
682 LinkGraphID lg = ge.link_graph;
683 if (!LinkGraph::IsValidID(lg)) continue;
684 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
689 * Common part of building various station parts and possibly attaching them to an existing one.
690 * @param[in,out] st Station to attach to
691 * @param flags Command flags
692 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
693 * @param area Area occupied by the new part
694 * @param name_class Station naming class to use to generate the new station's name
695 * @return Command error that occurred, if any
697 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
699 /* Find a deleted station close to us */
700 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
702 if (*st != nullptr) {
703 if ((*st)->owner != _current_company) {
704 return_cmd_error(CMD_ERROR);
707 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
708 if (ret.Failed()) return ret;
709 } else {
710 /* allocate and initialize new station */
711 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
713 if (flags & DC_EXEC) {
714 *st = new Station(area.tile);
715 _station_kdtree.Insert((*st)->index);
717 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
718 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
720 if (Company::IsValidID(_current_company)) {
721 SetBit((*st)->town->have_ratings, _current_company);
725 return CommandCost();
729 * This is called right after a station was deleted.
730 * It checks if the whole station is free of substations, and if so, the station will be
731 * deleted after a little while.
732 * @param st Station
734 static void DeleteStationIfEmpty(BaseStation *st)
736 if (!st->IsInUse()) {
737 st->delete_ctr = 0;
738 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
740 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
741 UpdateStationSignCoord(st);
745 * After adding/removing tiles to station, update some station-related stuff.
746 * @param adding True if adding tiles, false if removing them.
747 * @param type StationType being modified.
749 void Station::AfterStationTileSetChange(bool adding, StationType type)
751 this->UpdateVirtCoord();
752 DirtyCompanyInfrastructureWindows(this->owner);
754 if (adding) {
755 this->RecomputeCatchment();
756 MarkCatchmentTilesDirty();
757 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
758 } else {
759 MarkCatchmentTilesDirty();
762 switch (type) {
763 case STATION_RAIL:
764 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
765 break;
766 case STATION_AIRPORT:
767 break;
768 case STATION_TRUCK:
769 case STATION_BUS:
770 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
771 break;
772 case STATION_DOCK:
773 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
774 break;
775 default: NOT_REACHED();
778 if (adding) {
779 UpdateStationAcceptance(this, false);
780 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
781 } else {
782 DeleteStationIfEmpty(this);
783 this->RecomputeCatchment();
788 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
791 * Checks if the given tile is buildable, flat and has a certain height.
792 * @param tile TileIndex to check.
793 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
794 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
795 * @param allow_steep Whether steep slopes are allowed.
796 * @param check_bridge Check for the existence of a bridge.
797 * @return The cost in case of success, or an error code if it failed.
799 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
801 if (check_bridge && IsBridgeAbove(tile)) {
802 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
805 CommandCost ret = EnsureNoVehicleOnGround(tile);
806 if (ret.Failed()) return ret;
808 int z;
809 Slope tileh = GetTileSlope(tile, &z);
811 /* Prohibit building if
812 * 1) The tile is "steep" (i.e. stretches two height levels).
813 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
815 if ((!allow_steep && IsSteepSlope(tileh)) ||
816 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
817 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
820 CommandCost cost(EXPENSES_CONSTRUCTION);
821 int flat_z = z + GetSlopeMaxZ(tileh);
822 if (tileh != SLOPE_FLAT) {
823 /* Forbid building if the tile faces a slope in a invalid direction. */
824 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
825 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
826 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
829 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
832 /* The level of this tile must be equal to allowed_z. */
833 if (allowed_z < 0) {
834 /* First tile. */
835 allowed_z = flat_z;
836 } else if (allowed_z != flat_z) {
837 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
840 return cost;
844 * Checks if an airport can be built at the given location and clear the area.
845 * @param tile_iter Airport tile iterator.
846 * @param flags Operation to perform.
847 * @return The cost in case of success, or an error code if it failed.
849 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
851 CommandCost cost(EXPENSES_CONSTRUCTION);
852 int allowed_z = -1;
854 for (; tile_iter != INVALID_TILE; ++tile_iter) {
855 CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
856 if (ret.Failed()) return ret;
857 cost.AddCost(ret);
859 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
860 if (ret.Failed()) return ret;
861 cost.AddCost(ret);
864 return cost;
868 * Checks if a rail station can be built at the given area.
869 * @param tile_area Area to check.
870 * @param flags Operation to perform.
871 * @param axis Rail station axis.
872 * @param station StationID to be queried and returned if available.
873 * @param rt The rail type to check for (overbuilding rail stations over rail).
874 * @param affected_vehicles List of trains with PBS reservations on the tiles
875 * @param spec_class Station class.
876 * @param spec_index Index into the station class.
877 * @param plat_len Platform length.
878 * @param numtracks Number of platforms.
879 * @return The cost in case of success, or an error code if it failed.
881 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
883 CommandCost cost(EXPENSES_CONSTRUCTION);
884 int allowed_z = -1;
885 uint invalid_dirs = 5 << axis;
887 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
888 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
890 for (TileIndex tile_cur : tile_area) {
891 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
892 if (ret.Failed()) return ret;
893 cost.AddCost(ret);
895 if (slope_cb) {
896 /* Do slope check if requested. */
897 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
898 if (ret.Failed()) return ret;
901 /* if station is set, then we have special handling to allow building on top of already existing stations.
902 * so station points to INVALID_STATION if we can build on any station.
903 * Or it points to a station if we're only allowed to build on exactly that station. */
904 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
905 if (!IsRailStation(tile_cur)) {
906 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
907 } else {
908 StationID st = GetStationIndex(tile_cur);
909 if (*station == INVALID_STATION) {
910 *station = st;
911 } else if (*station != st) {
912 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
915 } else {
916 /* Rail type is only valid when building a railway station; if station to
917 * build isn't a rail station it's INVALID_RAILTYPE. */
918 if (rt != INVALID_RAILTYPE &&
919 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
920 HasPowerOnRail(GetRailType(tile_cur), rt)) {
921 /* Allow overbuilding if the tile:
922 * - has rail, but no signals
923 * - it has exactly one track
924 * - the track is in line with the station
925 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
927 TrackBits tracks = GetTrackBits(tile_cur);
928 Track track = RemoveFirstTrack(&tracks);
929 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
931 if (tracks == TRACK_BIT_NONE && track == expected_track) {
932 /* Check for trains having a reservation for this tile. */
933 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
934 Train *v = GetTrainForReservation(tile_cur, track);
935 if (v != nullptr) {
936 affected_vehicles.push_back(v);
939 ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
940 if (ret.Failed()) return ret;
941 cost.AddCost(ret);
942 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
943 continue;
946 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
947 if (ret.Failed()) return ret;
948 cost.AddCost(ret);
952 return cost;
956 * Checks if a road stop can be built at the given tile.
957 * @param tile_area Area to check.
958 * @param flags Operation to perform.
959 * @param invalid_dirs Prohibited directions (set of DiagDirections).
960 * @param is_drive_through True if trying to build a drive-through station.
961 * @param is_truck_stop True when building a truck stop, false otherwise.
962 * @param axis Axis of a drive-through road stop.
963 * @param station StationID to be queried and returned if available.
964 * @param rt Road type to build.
965 * @return The cost in case of success, or an error code if it failed.
967 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)
969 CommandCost cost(EXPENSES_CONSTRUCTION);
970 int allowed_z = -1;
972 for (TileIndex cur_tile : tile_area) {
973 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
974 if (ret.Failed()) return ret;
975 cost.AddCost(ret);
977 /* If station is set, then we have special handling to allow building on top of already existing stations.
978 * Station points to INVALID_STATION if we can build on any station.
979 * Or it points to a station if we're only allowed to build on exactly that station. */
980 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
981 if (!IsRoadStop(cur_tile)) {
982 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
983 } else {
984 if (is_truck_stop != IsTruckStop(cur_tile) ||
985 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
986 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
988 /* Drive-through station in the wrong direction. */
989 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
990 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
992 StationID st = GetStationIndex(cur_tile);
993 if (*station == INVALID_STATION) {
994 *station = st;
995 } else if (*station != st) {
996 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
999 } else {
1000 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1001 /* Road bits in the wrong direction. */
1002 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1003 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1004 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1005 switch (CountBits(rb)) {
1006 case 1:
1007 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1009 case 2:
1010 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1011 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1013 default: // 3 or 4
1014 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1018 if (build_over_road) {
1019 /* There is a road, check if we can build road+tram stop over it. */
1020 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1021 if (road_rt != INVALID_ROADTYPE) {
1022 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1023 if (road_owner == OWNER_TOWN) {
1024 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1025 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1026 ret = CheckOwnership(road_owner);
1027 if (ret.Failed()) return ret;
1029 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1031 if (RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1033 if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1034 ret = CheckOwnership(road_owner);
1035 if (ret.Failed()) return ret;
1038 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1039 } else if (RoadTypeIsRoad(rt)) {
1040 cost.AddCost(RoadBuildCost(rt) * 2);
1043 /* There is a tram, check if we can build road+tram stop over it. */
1044 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1045 if (tram_rt != INVALID_ROADTYPE) {
1046 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1047 if (Company::IsValidID(tram_owner) &&
1048 (!_settings_game.construction.road_stop_on_competitor_road ||
1049 /* Disallow breaking end-of-line of someone else
1050 * so trams can still reverse on this tile. */
1051 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1052 ret = CheckOwnership(tram_owner);
1053 if (ret.Failed()) return ret;
1055 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1057 if (RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1059 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1060 } else if (RoadTypeIsTram(rt)) {
1061 cost.AddCost(RoadBuildCost(rt) * 2);
1063 } else {
1064 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1065 if (ret.Failed()) return ret;
1066 cost.AddCost(ret);
1067 cost.AddCost(RoadBuildCost(rt) * 2);
1072 return cost;
1076 * Check whether we can expand the rail part of the given station.
1077 * @param st the station to expand
1078 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1079 * @return Succeeded or failed command.
1081 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
1083 TileArea cur_ta = st->train_station;
1085 /* determine new size of train station region.. */
1086 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1087 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1088 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1089 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1090 new_ta.tile = TileXY(x, y);
1092 /* make sure the final size is not too big. */
1093 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1094 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1097 return CommandCost();
1100 static inline byte *CreateSingle(byte *layout, int n)
1102 int i = n;
1103 do *layout++ = 0; while (--i);
1104 layout[((n - 1) >> 1) - n] = 2;
1105 return layout;
1108 static inline byte *CreateMulti(byte *layout, int n, byte b)
1110 int i = n;
1111 do *layout++ = b; while (--i);
1112 if (n > 4) {
1113 layout[0 - n] = 0;
1114 layout[n - 1 - n] = 0;
1116 return layout;
1120 * Create the station layout for the given number of tracks and platform length.
1121 * @param layout The layout to write to.
1122 * @param numtracks The number of tracks to write.
1123 * @param plat_len The length of the platforms.
1124 * @param statspec The specification of the station to (possibly) get the layout from.
1126 void GetStationLayout(byte *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1128 if (statspec != nullptr && statspec->layouts.size() >= plat_len &&
1129 statspec->layouts[plat_len - 1].size() >= numtracks &&
1130 !statspec->layouts[plat_len - 1][numtracks - 1].empty()) {
1131 /* Custom layout defined, follow it. */
1132 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1].data(),
1133 static_cast<size_t>(plat_len) * numtracks);
1134 return;
1137 if (plat_len == 1) {
1138 CreateSingle(layout, numtracks);
1139 } else {
1140 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1141 int n = numtracks >> 1;
1143 while (--n >= 0) {
1144 layout = CreateMulti(layout, plat_len, 4);
1145 layout = CreateMulti(layout, plat_len, 6);
1151 * Find a nearby station that joins this station.
1152 * @tparam T the class to find a station for
1153 * @tparam error_message the error message when building a station on top of others
1154 * @param existing_station an existing station we build over
1155 * @param station_to_join the station to join to
1156 * @param adjacent whether adjacent stations are allowed
1157 * @param ta the area of the newly build station
1158 * @param st 'return' pointer for the found station
1159 * @return command cost with the error or 'okay'
1161 template <class T, StringID error_message>
1162 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1164 assert(*st == nullptr);
1165 bool check_surrounding = true;
1167 if (_settings_game.station.adjacent_stations) {
1168 if (existing_station != INVALID_STATION) {
1169 if (adjacent && existing_station != station_to_join) {
1170 /* You can't build an adjacent station over the top of one that
1171 * already exists. */
1172 return_cmd_error(error_message);
1173 } else {
1174 /* Extend the current station, and don't check whether it will
1175 * be near any other stations. */
1176 *st = T::GetIfValid(existing_station);
1177 check_surrounding = (*st == nullptr);
1179 } else {
1180 /* There's no station here. Don't check the tiles surrounding this
1181 * one if the company wanted to build an adjacent station. */
1182 if (adjacent) check_surrounding = false;
1186 if (check_surrounding) {
1187 /* Make sure there is no more than one other station around us that is owned by us. */
1188 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st);
1189 if (ret.Failed()) return ret;
1192 /* Distant join */
1193 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1195 return CommandCost();
1199 * Find a nearby station that joins this station.
1200 * @param existing_station an existing station we build over
1201 * @param station_to_join the station to join to
1202 * @param adjacent whether adjacent stations are allowed
1203 * @param ta the area of the newly build station
1204 * @param st 'return' pointer for the found station
1205 * @return command cost with the error or 'okay'
1207 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1209 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1213 * Find a nearby waypoint that joins this waypoint.
1214 * @param existing_waypoint an existing waypoint we build over
1215 * @param waypoint_to_join the waypoint to join to
1216 * @param adjacent whether adjacent waypoints are allowed
1217 * @param ta the area of the newly build waypoint
1218 * @param wp 'return' pointer for the found waypoint
1219 * @return command cost with the error or 'okay'
1221 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1223 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1227 * Clear platform reservation during station building/removing.
1228 * @param v vehicle which holds reservation
1230 static void FreeTrainReservation(Train *v)
1232 FreeTrainTrackReservation(v);
1233 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1234 v = v->Last();
1235 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1239 * Restore platform reservation during station building/removing.
1240 * @param v vehicle which held reservation
1242 static void RestoreTrainReservation(Train *v)
1244 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1245 TryPathReserve(v, true, true);
1246 v = v->Last();
1247 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1251 * Calculates cost of new rail stations within the area.
1252 * @param tile_area Area to check.
1253 * @param flags Operation to perform.
1254 * @param axis Rail station axis.
1255 * @param station StationID to be queried and returned if available.
1256 * @param rt The rail type to check for (overbuilding rail stations over rail).
1257 * @param affected_vehicles List of trains with PBS reservations on the tiles
1258 * @param spec_class Station class.
1259 * @param spec_index Index into the station class.
1260 * @param plat_len Platform length.
1261 * @param numtracks Number of platforms.
1262 * @return The cost in case of success, or an error code if it failed.
1264 static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, byte plat_len, byte numtracks)
1266 CommandCost cost(EXPENSES_CONSTRUCTION);
1267 bool length_price_ready = true;
1268 byte tracknum = 0;
1269 for (TileIndex cur_tile : tile_area) {
1270 /* Clear the land below the station. */
1271 CommandCost ret = CheckFlatLandRailStation(TileArea(cur_tile, 1, 1), flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1272 if (ret.Failed()) return ret;
1274 /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1275 if (tracknum == numtracks) {
1276 length_price_ready = true;
1277 tracknum = 0;
1278 } else {
1279 tracknum++;
1282 /* AddCost for new or rotated rail stations. */
1283 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1285 cost.AddCost(ret);
1286 cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1287 cost.AddCost(RailBuildCost(rt));
1289 if (length_price_ready) {
1290 cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1291 length_price_ready = false;
1296 return cost;
1300 * Build rail station
1301 * @param flags operation to perform
1302 * @param tile_org northern most position of station dragging/placement
1303 * @param rt railtype
1304 * @param axis orientation (Axis)
1305 * @param numtracks number of tracks
1306 * @param plat_len platform length
1307 * @param spec_class custom station class
1308 * @param spec_index custom station id
1309 * @param station_to_join station ID to join (NEW_STATION if build new one)
1310 * @param adjacent allow stations directly adjacent to other stations.
1311 * @return the cost of this operation or an error
1313 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, byte numtracks, byte plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1315 /* Does the authority allow this? */
1316 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1317 if (ret.Failed()) return ret;
1319 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1321 /* Check if the given station class is valid */
1322 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1323 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1324 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1326 int w_org, h_org;
1327 if (axis == AXIS_X) {
1328 w_org = plat_len;
1329 h_org = numtracks;
1330 } else {
1331 h_org = plat_len;
1332 w_org = numtracks;
1335 bool reuse = (station_to_join != NEW_STATION);
1336 if (!reuse) station_to_join = INVALID_STATION;
1337 bool distant_join = (station_to_join != INVALID_STATION);
1339 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1341 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1343 /* these values are those that will be stored in train_tile and station_platforms */
1344 TileArea new_location(tile_org, w_org, h_org);
1346 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1347 StationID est = INVALID_STATION;
1348 std::vector<Train *> affected_vehicles;
1349 /* Add construction and clearing expenses. */
1350 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1351 if (cost.Failed()) return cost;
1353 Station *st = nullptr;
1354 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1355 if (ret.Failed()) return ret;
1357 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1358 if (ret.Failed()) return ret;
1360 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1361 ret = CanExpandRailStation(st, new_location);
1362 if (ret.Failed()) return ret;
1365 /* Check if we can allocate a custom stationspec to this station */
1366 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1367 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1368 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1370 if (statspec != nullptr) {
1371 /* Perform NewStation checks */
1373 /* Check if the station size is permitted */
1374 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) {
1375 return CMD_ERROR;
1378 /* Check if the station is buildable */
1379 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1380 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1381 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1385 if (flags & DC_EXEC) {
1386 TileIndexDiff tile_delta;
1387 byte numtracks_orig;
1388 Track track;
1390 st->train_station = new_location;
1391 st->AddFacility(FACIL_TRAIN, new_location.tile);
1393 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1395 if (statspec != nullptr) {
1396 /* Include this station spec's animation trigger bitmask
1397 * in the station's cached copy. */
1398 st->cached_anim_triggers |= statspec->animation.triggers;
1401 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1402 track = AxisToTrack(axis);
1404 std::vector<byte> layouts(numtracks * plat_len);
1405 GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1407 numtracks_orig = numtracks;
1409 Company *c = Company::Get(st->owner);
1410 size_t layout_idx = 0;
1411 TileIndex tile_track = tile_org;
1412 do {
1413 TileIndex tile = tile_track;
1414 int w = plat_len;
1415 do {
1416 byte layout = layouts[layout_idx++];
1417 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1418 /* Check for trains having a reservation for this tile. */
1419 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1420 if (v != nullptr) {
1421 affected_vehicles.push_back(v);
1422 FreeTrainReservation(v);
1426 /* Railtype can change when overbuilding. */
1427 if (IsRailStationTile(tile)) {
1428 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1429 c->infrastructure.station--;
1432 /* Remove animation if overbuilding */
1433 DeleteAnimatedTile(tile);
1434 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1435 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1436 /* Free the spec if we overbuild something */
1437 DeallocateSpecFromStation(st, old_specindex);
1439 SetCustomStationSpecIndex(tile, specindex);
1440 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1441 SetAnimationFrame(tile, 0);
1443 if (statspec != nullptr) {
1444 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1445 uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1447 /* As the station is not yet completely finished, the station does not yet exist. */
1448 uint16_t callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1449 if (callback != CALLBACK_FAILED) {
1450 if (callback < 8) {
1451 SetStationGfx(tile, (callback & ~1) + axis);
1452 } else {
1453 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1457 /* Trigger station animation -- after building? */
1458 TriggerStationAnimation(st, tile, SAT_BUILT);
1461 /* Should be the same as layout but axis component could be wrong... */
1462 StationGfx gfx = GetStationGfx(tile);
1463 bool blocked = statspec != nullptr && HasBit(statspec->blocked, gfx);
1464 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1465 bool pylons = statspec != nullptr ? HasBit(statspec->pylons, gfx) : gfx < 4;
1466 bool wires = statspec == nullptr || !HasBit(statspec->wires, gfx);
1468 SetStationTileBlocked(tile, blocked);
1469 SetStationTileHavePylons(tile, pylons);
1470 SetStationTileHaveWires(tile, wires);
1472 if (!blocked) c->infrastructure.rail[rt]++;
1473 c->infrastructure.station++;
1475 tile += tile_delta;
1476 } while (--w);
1477 AddTrackToSignalBuffer(tile_track, track, _current_company);
1478 YapfNotifyTrackLayoutChange(tile_track, track);
1479 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1480 } while (--numtracks);
1482 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1483 /* Restore reservations of trains. */
1484 RestoreTrainReservation(affected_vehicles[i]);
1487 /* Check whether we need to expand the reservation of trains already on the station. */
1488 TileArea update_reservation_area;
1489 if (axis == AXIS_X) {
1490 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1491 } else {
1492 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1495 for (TileIndex tile : update_reservation_area) {
1496 /* Don't even try to make eye candy parts reserved. */
1497 if (IsStationTileBlocked(tile)) continue;
1499 DiagDirection dir = AxisToDiagDir(axis);
1500 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1501 TileIndex platform_begin = tile;
1502 TileIndex platform_end = tile;
1504 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1505 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1506 platform_begin = next_tile;
1508 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1509 platform_end = next_tile;
1512 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1513 bool reservation = false;
1514 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1515 reservation = HasStationReservation(t);
1518 if (reservation) {
1519 SetRailStationPlatformReservation(platform_begin, dir, true);
1523 st->MarkTilesDirty(false);
1524 st->AfterStationTileSetChange(true, STATION_RAIL);
1527 return cost;
1530 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1532 restart:
1534 /* too small? */
1535 if (ta.w != 0 && ta.h != 0) {
1536 /* check the left side, x = constant, y changes */
1537 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1538 /* the left side is unused? */
1539 if (++i == ta.h) {
1540 ta.tile += TileDiffXY(1, 0);
1541 ta.w--;
1542 goto restart;
1546 /* check the right side, x = constant, y changes */
1547 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1548 /* the right side is unused? */
1549 if (++i == ta.h) {
1550 ta.w--;
1551 goto restart;
1555 /* check the upper side, y = constant, x changes */
1556 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1557 /* the left side is unused? */
1558 if (++i == ta.w) {
1559 ta.tile += TileDiffXY(0, 1);
1560 ta.h--;
1561 goto restart;
1565 /* check the lower side, y = constant, x changes */
1566 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1567 /* the left side is unused? */
1568 if (++i == ta.w) {
1569 ta.h--;
1570 goto restart;
1573 } else {
1574 ta.Clear();
1577 return ta;
1580 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1582 return st->TileBelongsToRailStation(tile);
1585 static void MakeRailStationAreaSmaller(BaseStation *st)
1587 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1590 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1592 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1595 static void MakeShipStationAreaSmaller(Station *st)
1597 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1598 UpdateStationDockingTiles(st);
1602 * Remove a number of tiles from any rail station within the area.
1603 * @param ta the area to clear station tile from.
1604 * @param affected_stations the stations affected.
1605 * @param flags the command flags.
1606 * @param removal_cost the cost for removing the tile, including the rail.
1607 * @param keep_rail whether to keep the rail of the station.
1608 * @tparam T the type of station to remove.
1609 * @return the number of cleared tiles or an error.
1611 template <class T>
1612 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1614 /* Count of the number of tiles removed */
1615 int quantity = 0;
1616 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1617 /* Accumulator for the errors seen during clearing. If no errors happen,
1618 * and the quantity is 0 there is no station. Otherwise it will be one
1619 * of the other error that got accumulated. */
1620 CommandCost error;
1622 /* Do the action for every tile into the area */
1623 for (TileIndex tile : ta) {
1624 /* Make sure the specified tile is a rail station */
1625 if (!HasStationTileRail(tile)) continue;
1627 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1628 CommandCost ret = EnsureNoVehicleOnGround(tile);
1629 error.AddCost(ret);
1630 if (ret.Failed()) continue;
1632 /* Check ownership of station */
1633 T *st = T::GetByTile(tile);
1634 if (st == nullptr) continue;
1636 if (_current_company != OWNER_WATER) {
1637 ret = CheckOwnership(st->owner);
1638 error.AddCost(ret);
1639 if (ret.Failed()) continue;
1642 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1643 quantity++;
1645 if (keep_rail || IsStationTileBlocked(tile)) {
1646 /* Don't refund the 'steel' of the track when we keep the
1647 * rail, or when the tile didn't have any rail at all. */
1648 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1651 if (flags & DC_EXEC) {
1652 /* read variables before the station tile is removed */
1653 uint specindex = GetCustomStationSpecIndex(tile);
1654 Track track = GetRailStationTrack(tile);
1655 Owner owner = GetTileOwner(tile);
1656 RailType rt = GetRailType(tile);
1657 Train *v = nullptr;
1659 if (HasStationReservation(tile)) {
1660 v = GetTrainForReservation(tile, track);
1661 if (v != nullptr) FreeTrainReservation(v);
1664 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1665 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1667 DoClearSquare(tile);
1668 DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1669 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1670 Company::Get(owner)->infrastructure.station--;
1671 DirtyCompanyInfrastructureWindows(owner);
1673 st->rect.AfterRemoveTile(st, tile);
1674 AddTrackToSignalBuffer(tile, track, owner);
1675 YapfNotifyTrackLayoutChange(tile, track);
1677 DeallocateSpecFromStation(st, specindex);
1679 include(affected_stations, st);
1681 if (v != nullptr) RestoreTrainReservation(v);
1685 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1687 for (T *st : affected_stations) {
1689 /* now we need to make the "spanned" area of the railway station smaller
1690 * if we deleted something at the edges.
1691 * we also need to adjust train_tile. */
1692 MakeRailStationAreaSmaller(st);
1693 UpdateStationSignCoord(st);
1695 /* if we deleted the whole station, delete the train facility. */
1696 if (st->train_station.tile == INVALID_TILE) {
1697 st->facilities &= ~FACIL_TRAIN;
1698 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
1699 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1700 MarkCatchmentTilesDirty();
1701 st->UpdateVirtCoord();
1702 DeleteStationIfEmpty(st);
1706 total_cost.AddCost(quantity * removal_cost);
1707 return total_cost;
1711 * Remove a single tile from a rail station.
1712 * This allows for custom-built station with holes and weird layouts
1713 * @param flags operation to perform
1714 * @param start tile of station piece to remove
1715 * @param end other edge of the rect to remove
1716 * @param keep_rail if set keep the rail
1717 * @return the cost of this operation or an error
1719 CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1721 if (end == 0) end = start;
1722 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1724 TileArea ta(start, end);
1725 std::vector<Station *> affected_stations;
1727 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1728 if (ret.Failed()) return ret;
1730 /* Do all station specific functions here. */
1731 for (Station *st : affected_stations) {
1733 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1734 st->MarkTilesDirty(false);
1735 MarkCatchmentTilesDirty();
1736 st->RecomputeCatchment();
1739 /* Now apply the rail cost to the number that we deleted */
1740 return ret;
1744 * Remove a single tile from a waypoint.
1745 * This allows for custom-built waypoint with holes and weird layouts
1746 * @param flags operation to perform
1747 * @param start tile of waypoint piece to remove
1748 * @param end other edge of the rect to remove
1749 * @param keep_rail if set keep the rail
1750 * @return the cost of this operation or an error
1752 CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1754 if (end == 0) end = start;
1755 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1757 TileArea ta(start, end);
1758 std::vector<Waypoint *> affected_stations;
1760 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1765 * Remove a rail station/waypoint
1766 * @param st The station/waypoint to remove the rail part from
1767 * @param flags operation to perform
1768 * @param removal_cost the cost for removing a tile
1769 * @tparam T the type of station to remove
1770 * @return cost or failure of operation
1772 template <class T>
1773 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1775 /* Current company owns the station? */
1776 if (_current_company != OWNER_WATER) {
1777 CommandCost ret = CheckOwnership(st->owner);
1778 if (ret.Failed()) return ret;
1781 /* determine width and height of platforms */
1782 TileArea ta = st->train_station;
1784 assert(ta.w != 0 && ta.h != 0);
1786 CommandCost cost(EXPENSES_CONSTRUCTION);
1787 /* clear all areas of the station */
1788 for (TileIndex tile : ta) {
1789 /* only remove tiles that are actually train station tiles */
1790 if (st->TileBelongsToRailStation(tile)) {
1791 std::vector<T*> affected_stations; // dummy
1792 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1793 if (ret.Failed()) return ret;
1794 cost.AddCost(ret);
1798 return cost;
1802 * Remove a rail station
1803 * @param tile Tile of the station.
1804 * @param flags operation to perform
1805 * @return cost or failure of operation
1807 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1809 /* if there is flooding, remove platforms tile by tile */
1810 if (_current_company == OWNER_WATER) {
1811 return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1814 Station *st = Station::GetByTile(tile);
1815 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1817 if (flags & DC_EXEC) st->RecomputeCatchment();
1819 return cost;
1823 * Remove a rail waypoint
1824 * @param tile Tile of the waypoint.
1825 * @param flags operation to perform
1826 * @return cost or failure of operation
1828 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1830 /* if there is flooding, remove waypoints tile by tile */
1831 if (_current_company == OWNER_WATER) {
1832 return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1835 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1840 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1841 * @param st The Station to do the whole procedure for
1842 * @return a pointer to where to link a new RoadStop*
1844 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1846 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1848 if (*primary_stop == nullptr) {
1849 /* we have no roadstop of the type yet, so write a "primary stop" */
1850 return primary_stop;
1851 } else {
1852 /* there are stops already, so append to the end of the list */
1853 RoadStop *stop = *primary_stop;
1854 while (stop->next != nullptr) stop = stop->next;
1855 return &stop->next;
1859 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1862 * Find a nearby station that joins this road stop.
1863 * @param existing_stop an existing road stop we build over
1864 * @param station_to_join the station to join to
1865 * @param adjacent whether adjacent stations are allowed
1866 * @param ta the area of the newly build station
1867 * @param st 'return' pointer for the found station
1868 * @return command cost with the error or 'okay'
1870 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1872 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1876 * Calculates cost of new road stops within the area.
1877 * @param tile_area Area to check.
1878 * @param flags Operation to perform.
1879 * @param is_drive_through True if trying to build a drive-through station.
1880 * @param is_truck_stop True when building a truck stop, false otherwise.
1881 * @param axis Axis of a drive-through road stop.
1882 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1883 * @param station StationID to be queried and returned if available.
1884 * @param rt Road type to build.
1885 * @param unit_cost The cost to build one road stop of the current type.
1886 * @return The cost in case of success, or an error code if it failed.
1888 static CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, bool is_truck_stop, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
1890 CommandCost cost(EXPENSES_CONSTRUCTION);
1891 /* Check every tile in the area. */
1892 for (TileIndex cur_tile : tile_area) {
1893 uint invalid_dirs = 0;
1894 if (is_drive_through) {
1895 SetBit(invalid_dirs, AxisToDiagDir(axis));
1896 SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1897 } else {
1898 SetBit(invalid_dirs, ddir);
1900 CommandCost ret = CheckFlatLandRoadStop(TileArea(cur_tile, cur_tile), flags, invalid_dirs, is_drive_through, is_truck_stop, axis, est, rt);
1901 if (ret.Failed()) return ret;
1903 bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile);
1905 /* Only add costs if a stop doesn't already exist in the location */
1906 if (!is_preexisting_roadstop) {
1907 cost.AddCost(ret);
1908 cost.AddCost(unit_cost);
1912 return cost;
1916 * Build a bus or truck stop.
1917 * @param flags Operation to perform.
1918 * @param tile Northernmost tile of the stop.
1919 * @param width Width of the road stop.
1920 * @param length Length of the road stop.
1921 * @param stop_type Type of road stop (bus/truck).
1922 * @param is_drive_through False for normal stops, true for drive-through.
1923 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1924 * @param rt The roadtype.
1925 * @param spec_class Road stop spec class.
1926 * @param spec_index Road stop spec index.
1927 * @param station_to_join Station ID to join (NEW_STATION if build new one).
1928 * @param adjacent Allow stations directly adjacent to other stations.
1929 * @return The cost of this operation or an error.
1931 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1932 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1934 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1935 bool reuse = (station_to_join != NEW_STATION);
1936 if (!reuse) station_to_join = INVALID_STATION;
1937 bool distant_join = (station_to_join != INVALID_STATION);
1939 /* Check if the given station class is valid */
1940 if ((uint)spec_class >= RoadStopClass::GetClassCount() || spec_class == ROADSTOP_CLASS_WAYP) return CMD_ERROR;
1941 if (spec_index >= RoadStopClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1943 const RoadStopSpec *roadstopspec = RoadStopClass::Get(spec_class)->GetSpec(spec_index);
1944 if (roadstopspec != nullptr) {
1945 if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1946 if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1947 if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1950 /* Check if the requested road stop is too big */
1951 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1952 /* Check for incorrect width / length. */
1953 if (width == 0 || length == 0) return CMD_ERROR;
1954 /* Check if the first tile and the last tile are valid */
1955 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1957 TileArea roadstop_area(tile, width, length);
1959 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1961 /* Trams only have drive through stops */
1962 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
1964 Axis axis = DiagDirToAxis(ddir);
1966 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1967 if (ret.Failed()) return ret;
1969 bool is_truck_stop = stop_type != ROADSTOP_BUS;
1971 /* Total road stop cost. */
1972 Money unit_cost;
1973 if (roadstopspec != nullptr) {
1974 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
1975 } else {
1976 unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
1978 StationID est = INVALID_STATION;
1979 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop, axis, ddir, &est, rt, unit_cost);
1980 if (cost.Failed()) return cost;
1982 Station *st = nullptr;
1983 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
1984 if (ret.Failed()) return ret;
1986 /* Check if this number of road stops can be allocated. */
1987 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return_cmd_error(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1989 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1990 if (ret.Failed()) return ret;
1992 /* Check if we can allocate a custom stationspec to this station */
1993 int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
1994 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1996 if (roadstopspec != nullptr) {
1997 /* Perform NewGRF checks */
1999 /* Check if the road stop is buildable */
2000 if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2001 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2002 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2006 if (flags & DC_EXEC) {
2007 /* Check every tile in the area. */
2008 for (TileIndex cur_tile : roadstop_area) {
2009 /* Get existing road types and owners before any tile clearing */
2010 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2011 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2012 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2013 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2015 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
2016 RemoveRoadStop(cur_tile, flags, specindex);
2019 if (roadstopspec != nullptr) {
2020 /* Include this road stop spec's animation trigger bitmask
2021 * in the station's cached copy. */
2022 st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2025 RoadStop *road_stop = new RoadStop(cur_tile);
2026 /* Insert into linked list of RoadStops. */
2027 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2028 *currstop = road_stop;
2030 if (is_truck_stop) {
2031 st->truck_station.Add(cur_tile);
2032 } else {
2033 st->bus_station.Add(cur_tile);
2036 /* Initialize an empty station. */
2037 st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2039 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2041 RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2042 if (is_drive_through) {
2043 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2044 * bits first. */
2045 if (IsNormalRoadTile(cur_tile)) {
2046 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2047 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2050 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2051 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2053 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, road_rt, tram_rt, axis);
2054 road_stop->MakeDriveThrough();
2055 } else {
2056 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2057 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2058 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2060 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
2061 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
2062 Company::Get(st->owner)->infrastructure.station++;
2064 SetCustomRoadStopSpecIndex(cur_tile, specindex);
2065 if (roadstopspec != nullptr) {
2066 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2067 TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2070 MarkTileDirtyByTile(cur_tile);
2073 if (st != nullptr) {
2074 st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2077 return cost;
2081 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2083 if (v->type == VEH_ROAD) {
2084 /* Okay... we are a road vehicle on a drive through road stop.
2085 * But that road stop has just been removed, so we need to make
2086 * sure we are in a valid state... however, vehicles can also
2087 * turn on road stop tiles, so only clear the 'road stop' state
2088 * bits and only when the state was 'in road stop', otherwise
2089 * we'll end up clearing the turn around bits. */
2090 RoadVehicle *rv = RoadVehicle::From(v);
2091 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
2094 return nullptr;
2099 * Remove a bus station/truck stop
2100 * @param tile TileIndex been queried
2101 * @param flags operation to perform
2102 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2103 * @return cost or failure of operation
2105 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2107 Station *st = Station::GetByTile(tile);
2109 if (_current_company != OWNER_WATER) {
2110 CommandCost ret = CheckOwnership(st->owner);
2111 if (ret.Failed()) return ret;
2114 bool is_truck = IsTruckStop(tile);
2116 RoadStop **primary_stop;
2117 RoadStop *cur_stop;
2118 if (is_truck) { // truck stop
2119 primary_stop = &st->truck_stops;
2120 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2121 } else {
2122 primary_stop = &st->bus_stops;
2123 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2126 assert(cur_stop != nullptr);
2128 /* don't do the check for drive-through road stops when company bankrupts */
2129 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2130 /* remove the 'going through road stop' status from all vehicles on that tile */
2131 if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2132 } else {
2133 CommandCost ret = EnsureNoVehicleOnGround(tile);
2134 if (ret.Failed()) return ret;
2137 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2139 if (flags & DC_EXEC) {
2140 if (*primary_stop == cur_stop) {
2141 /* removed the first stop in the list */
2142 *primary_stop = cur_stop->next;
2143 /* removed the only stop? */
2144 if (*primary_stop == nullptr) {
2145 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2146 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2148 } else {
2149 /* tell the predecessor in the list to skip this stop */
2150 RoadStop *pred = *primary_stop;
2151 while (pred->next != cur_stop) pred = pred->next;
2152 pred->next = cur_stop->next;
2155 /* Update company infrastructure counts. */
2156 for (RoadTramType rtt : _roadtramtypes) {
2157 RoadType rt = GetRoadType(tile, rtt);
2158 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2161 Company::Get(st->owner)->infrastructure.station--;
2162 DirtyCompanyInfrastructureWindows(st->owner);
2164 DeleteAnimatedTile(tile);
2166 uint specindex = GetCustomRoadStopSpecIndex(tile);
2168 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2170 if (IsDriveThroughStopTile(tile)) {
2171 /* Clears the tile for us */
2172 cur_stop->ClearDriveThrough();
2173 } else {
2174 DoClearSquare(tile);
2177 delete cur_stop;
2179 /* Make sure no vehicle is going to the old roadstop */
2180 for (RoadVehicle *v : RoadVehicle::Iterate()) {
2181 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
2182 v->dest_tile == tile) {
2183 v->SetDestTile(v->GetOrderStationLocation(st->index));
2187 st->rect.AfterRemoveTile(st, tile);
2189 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2191 st->RemoveRoadStopTileData(tile);
2192 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2194 /* Update the tile area of the truck/bus stop */
2195 if (is_truck) {
2196 st->truck_station.Clear();
2197 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2198 } else {
2199 st->bus_station.Clear();
2200 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2204 Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2205 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2209 * Remove bus or truck stops.
2210 * @param flags Operation to perform.
2211 * @param tile Northernmost tile of the removal area.
2212 * @param width Width of the removal area.
2213 * @param height Height of the removal area.
2214 * @param stop_type Type of stop (bus/truck).
2215 * @param remove_road Remove roads of drive-through stops?
2216 * @return The cost of this operation or an error.
2218 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2220 if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2221 /* Check for incorrect width / height. */
2222 if (width == 0 || height == 0) return CMD_ERROR;
2223 /* Check if the first tile and the last tile are valid */
2224 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2225 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2226 if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2228 TileArea roadstop_area(tile, width, height);
2230 CommandCost cost(EXPENSES_CONSTRUCTION);
2231 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2232 bool had_success = false;
2234 for (TileIndex cur_tile : roadstop_area) {
2235 /* Make sure the specified tile is a road stop of the correct type */
2236 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || GetRoadStopType(cur_tile) != stop_type) continue;
2238 /* Save information on to-be-restored roads before the stop is removed. */
2239 RoadBits road_bits = ROAD_NONE;
2240 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2241 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2242 if (IsDriveThroughStopTile(cur_tile)) {
2243 for (RoadTramType rtt : _roadtramtypes) {
2244 road_type[rtt] = GetRoadType(cur_tile, rtt);
2245 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2246 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2247 /* If we don't want to preserve our roads then restore only roads of others. */
2248 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2250 road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2253 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2254 if (ret.Failed()) {
2255 last_error = ret;
2256 continue;
2258 cost.AddCost(ret);
2259 had_success = true;
2261 /* Restore roads. */
2262 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2263 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2264 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2266 /* Update company infrastructure counts. */
2267 int count = CountBits(road_bits);
2268 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2269 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2273 return had_success ? cost : last_error;
2277 * Get a possible noise reduction factor based on distance from town center.
2278 * The further you get, the less noise you generate.
2279 * So all those folks at city council can now happily slee... work in their offices
2280 * @param as airport information
2281 * @param distance minimum distance between town and airport
2282 * @return the noise that will be generated, according to distance
2284 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2286 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2287 * So no need to go any further*/
2288 if (as->noise_level < 2) return as->noise_level;
2290 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2291 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2292 * Basically, it says that the less tolerant a town is, the bigger the distance before
2293 * an actual decrease can be granted */
2294 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2296 /* now, we want to have the distance segmented using the distance judged bareable by town
2297 * This will give us the coefficient of reduction the distance provides. */
2298 uint noise_reduction = distance / town_tolerance_distance;
2300 /* If the noise reduction equals the airport noise itself, don't give it for free.
2301 * Otherwise, simply reduce the airport's level. */
2302 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2306 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2307 * If two towns have the same distance, town with lower index is returned.
2308 * @param as airport's description
2309 * @param rotation airport's rotation
2310 * @param tile origin tile (top corner of the airport)
2311 * @param it An iterator over all airport tiles (consumed)
2312 * @param[out] mindist Minimum distance to town
2313 * @return nearest town to airport
2315 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2317 assert(Town::GetNumItems() > 0);
2319 Town *nearest = nullptr;
2321 auto width = as->size_x;
2322 auto height = as->size_y;
2323 if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2325 uint perimeter_min_x = TileX(tile);
2326 uint perimeter_min_y = TileY(tile);
2327 uint perimeter_max_x = perimeter_min_x + width - 1;
2328 uint perimeter_max_y = perimeter_min_y + height - 1;
2330 mindist = UINT_MAX - 1; // prevent overflow
2332 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2333 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2334 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2335 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) {
2336 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2337 if (t == nullptr) continue;
2339 uint dist = DistanceManhattan(t->xy, cur_tile);
2340 if (dist == mindist && t->index < nearest->index) nearest = t;
2341 if (dist < mindist) {
2342 nearest = t;
2343 mindist = dist;
2348 return nearest;
2352 * Finds the town nearest to given existing airport. Based on minimal manhattan distance to any airport's tile.
2353 * If two towns have the same distance, town with lower index is returned.
2354 * @param station existing station with airport
2355 * @param[out] mindist Minimum distance to town
2356 * @return nearest town to airport
2358 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2360 return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2364 /** Recalculate the noise generated by the airports of each town */
2365 void UpdateAirportsNoise()
2367 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2369 for (const Station *st : Station::Iterate()) {
2370 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2371 uint dist;
2372 Town *nearest = AirportGetNearestTown(st, dist);
2373 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2379 * Place an Airport.
2380 * @param flags operation to perform
2381 * @param tile tile where airport will be built
2382 * @param airport_type airport type, @see airport.h
2383 * @param layout airport layout
2384 * @param station_to_join station ID to join (NEW_STATION if build new one)
2385 * @param allow_adjacent allow airports directly adjacent to other airports.
2386 * @return the cost of this operation or an error
2388 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, byte airport_type, byte layout, StationID station_to_join, bool allow_adjacent)
2390 bool reuse = (station_to_join != NEW_STATION);
2391 if (!reuse) station_to_join = INVALID_STATION;
2392 bool distant_join = (station_to_join != INVALID_STATION);
2394 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2396 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2398 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2399 if (ret.Failed()) return ret;
2401 /* Check if a valid, buildable airport was chosen for construction */
2402 const AirportSpec *as = AirportSpec::Get(airport_type);
2403 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2404 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2406 Direction rotation = as->rotation[layout];
2407 int w = as->size_x;
2408 int h = as->size_y;
2409 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2410 TileArea airport_area = TileArea(tile, w, h);
2412 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2413 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2416 AirportTileTableIterator tile_iter(as->table[layout], tile);
2417 CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2418 if (cost.Failed()) return cost;
2420 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2421 uint dist;
2422 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2423 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2425 /* Check if local auth would allow a new airport */
2426 StringID authority_refuse_message = STR_NULL;
2427 Town *authority_refuse_town = nullptr;
2429 if (_settings_game.economy.station_noise_level) {
2430 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2431 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2432 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2433 authority_refuse_town = nearest;
2435 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2436 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2437 uint num = 0;
2438 for (const Station *st : Station::Iterate()) {
2439 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2441 if (num >= 2) {
2442 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2443 authority_refuse_town = t;
2447 if (authority_refuse_message != STR_NULL) {
2448 SetDParam(0, authority_refuse_town->index);
2449 return_cmd_error(authority_refuse_message);
2452 Station *st = nullptr;
2453 ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2454 if (ret.Failed()) return ret;
2456 /* Distant join */
2457 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2459 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2460 if (ret.Failed()) return ret;
2462 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2463 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2466 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2467 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2470 if (flags & DC_EXEC) {
2471 /* Always add the noise, so there will be no need to recalculate when option toggles */
2472 nearest->noise_reached += newnoise_level;
2474 st->AddFacility(FACIL_AIRPORT, tile);
2475 st->airport.type = airport_type;
2476 st->airport.layout = layout;
2477 st->airport.flags = 0;
2478 st->airport.rotation = rotation;
2480 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2482 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2483 Tile t(iter);
2484 MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2485 SetStationTileRandomBits(t, GB(Random(), 0, 4));
2486 st->airport.Add(iter);
2488 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(t);
2491 /* Only call the animation trigger after all tiles have been built */
2492 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2493 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2496 UpdateAirplanesOnNewStation(st);
2498 Company::Get(st->owner)->infrastructure.airport++;
2500 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2501 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2503 if (_settings_game.economy.station_noise_level) {
2504 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2508 return cost;
2512 * Remove an airport
2513 * @param tile TileIndex been queried
2514 * @param flags operation to perform
2515 * @return cost or failure of operation
2517 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2519 Station *st = Station::GetByTile(tile);
2521 if (_current_company != OWNER_WATER) {
2522 CommandCost ret = CheckOwnership(st->owner);
2523 if (ret.Failed()) return ret;
2526 tile = st->airport.tile;
2528 CommandCost cost(EXPENSES_CONSTRUCTION);
2530 for (const Aircraft *a : Aircraft::Iterate()) {
2531 if (!a->IsNormalAircraft()) continue;
2532 if (a->targetairport == st->index && a->state != FLYING) {
2533 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2537 if (flags & DC_EXEC) {
2538 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2539 TileIndex tile_cur = st->airport.GetHangarTile(i);
2540 OrderBackup::Reset(tile_cur, false);
2541 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2544 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2545 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2546 * need of recalculation */
2547 uint dist;
2548 Town *nearest = AirportGetNearestTown(st, dist);
2549 nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2551 if (_settings_game.economy.station_noise_level) {
2552 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2556 for (TileIndex tile_cur : st->airport) {
2557 if (!st->TileBelongsToAirport(tile_cur)) continue;
2559 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2560 if (ret.Failed()) return ret;
2562 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2564 if (flags & DC_EXEC) {
2565 DeleteAnimatedTile(tile_cur);
2566 DoClearSquare(tile_cur);
2567 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2571 if (flags & DC_EXEC) {
2572 /* Clear the persistent storage. */
2573 delete st->airport.psa;
2575 st->rect.AfterRemoveRect(st, st->airport);
2577 st->airport.Clear();
2578 st->facilities &= ~FACIL_AIRPORT;
2579 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2581 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2583 Company::Get(st->owner)->infrastructure.airport--;
2585 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2587 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2590 return cost;
2594 * Open/close an airport to incoming aircraft.
2595 * @param flags Operation to perform.
2596 * @param station_id Station ID of the airport.
2597 * @return the cost of this operation or an error
2599 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2601 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2602 Station *st = Station::Get(station_id);
2604 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2606 CommandCost ret = CheckOwnership(st->owner);
2607 if (ret.Failed()) return ret;
2609 if (flags & DC_EXEC) {
2610 st->airport.flags ^= AIRPORT_CLOSED_block;
2611 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2613 return CommandCost();
2617 * Tests whether the company's vehicles have this station in orders
2618 * @param station station ID
2619 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2620 * @param company company ID
2622 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2624 for (const Vehicle *v : Vehicle::Iterate()) {
2625 if ((v->owner == company) == include_company) {
2626 for (const Order *order : v->Orders()) {
2627 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2628 return true;
2633 return false;
2636 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2637 {-1, 0},
2638 { 0, 0},
2639 { 0, 0},
2640 { 0, -1}
2642 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2643 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2646 * Build a dock/haven.
2647 * @param flags operation to perform
2648 * @param tile tile where dock will be built
2649 * @param station_to_join station ID to join (NEW_STATION if build new one)
2650 * @param adjacent allow docks directly adjacent to other docks.
2651 * @return the cost of this operation or an error
2653 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2655 bool reuse = (station_to_join != NEW_STATION);
2656 if (!reuse) station_to_join = INVALID_STATION;
2657 bool distant_join = (station_to_join != INVALID_STATION);
2659 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2661 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2662 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2663 direction = ReverseDiagDir(direction);
2665 /* Docks cannot be placed on rapids */
2666 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2668 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2669 if (ret.Failed()) return ret;
2671 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2673 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2674 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2675 if (ret.Failed()) return ret;
2676 cost.AddCost(ret);
2678 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2680 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2681 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2684 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2686 /* Get the water class of the water tile before it is cleared.*/
2687 WaterClass wc = GetWaterClass(tile_cur);
2689 bool add_cost = !IsWaterTile(tile_cur);
2690 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2691 if (ret.Failed()) return ret;
2692 if (add_cost) cost.AddCost(ret);
2694 tile_cur += TileOffsByDiagDir(direction);
2695 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2696 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2699 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2700 _dock_w_chk[direction], _dock_h_chk[direction]);
2702 /* middle */
2703 Station *st = nullptr;
2704 ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2705 if (ret.Failed()) return ret;
2707 /* Distant join */
2708 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2710 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2711 if (ret.Failed()) return ret;
2713 if (flags & DC_EXEC) {
2714 st->ship_station.Add(tile);
2715 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2716 st->ship_station.Add(flat_tile);
2717 st->AddFacility(FACIL_DOCK, tile);
2719 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2721 /* If the water part of the dock is on a canal, update infrastructure counts.
2722 * This is needed as we've cleared that tile before.
2723 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2724 * See: MakeWaterKeepingClass() */
2725 if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2726 Company::Get(st->owner)->infrastructure.water++;
2728 Company::Get(st->owner)->infrastructure.station += 2;
2730 MakeDock(tile, st->owner, st->index, direction, wc);
2731 UpdateStationDockingTiles(st);
2733 st->AfterStationTileSetChange(true, STATION_DOCK);
2736 return cost;
2739 void RemoveDockingTile(TileIndex t)
2741 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2742 TileIndex tile = t + TileOffsByDiagDir(d);
2743 if (!IsValidTile(tile)) continue;
2745 if (IsTileType(tile, MP_STATION)) {
2746 Station *st = Station::GetByTile(tile);
2747 if (st != nullptr) UpdateStationDockingTiles(st);
2748 } else if (IsTileType(tile, MP_INDUSTRY)) {
2749 Station *neutral = Industry::GetByTile(tile)->neutral_station;
2750 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2756 * Clear docking tile status from tiles around a removed dock, if the tile has
2757 * no neighbours which would keep it as a docking tile.
2758 * @param tile Ex-dock tile to check.
2760 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2762 assert(IsValidTile(tile));
2764 /* Clear and maybe re-set docking tile */
2765 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2766 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2767 if (!IsValidTile(docking_tile)) continue;
2769 if (IsPossibleDockingTile(docking_tile)) {
2770 SetDockingTile(docking_tile, false);
2771 CheckForDockingTile(docking_tile);
2777 * Find the part of a dock that is land-based
2778 * @param t Dock tile to find land part of
2779 * @return tile of land part of dock
2781 static TileIndex FindDockLandPart(TileIndex t)
2783 assert(IsDockTile(t));
2785 StationGfx gfx = GetStationGfx(t);
2786 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2788 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2789 TileIndex tile = t + TileOffsByDiagDir(d);
2790 if (!IsValidTile(tile)) continue;
2791 if (!IsDockTile(tile)) continue;
2792 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2795 return INVALID_TILE;
2799 * Remove a dock
2800 * @param tile TileIndex been queried
2801 * @param flags operation to perform
2802 * @return cost or failure of operation
2804 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2806 Station *st = Station::GetByTile(tile);
2807 CommandCost ret = CheckOwnership(st->owner);
2808 if (ret.Failed()) return ret;
2810 if (!IsDockTile(tile)) return CMD_ERROR;
2812 TileIndex tile1 = FindDockLandPart(tile);
2813 if (tile1 == INVALID_TILE) return CMD_ERROR;
2814 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2816 ret = EnsureNoVehicleOnGround(tile1);
2817 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2818 if (ret.Failed()) return ret;
2820 if (flags & DC_EXEC) {
2821 DoClearSquare(tile1);
2822 MarkTileDirtyByTile(tile1);
2823 MakeWaterKeepingClass(tile2, st->owner);
2825 st->rect.AfterRemoveTile(st, tile1);
2826 st->rect.AfterRemoveTile(st, tile2);
2828 MakeShipStationAreaSmaller(st);
2829 if (st->ship_station.tile == INVALID_TILE) {
2830 st->ship_station.Clear();
2831 st->docking_station.Clear();
2832 st->facilities &= ~FACIL_DOCK;
2833 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2836 Company::Get(st->owner)->infrastructure.station -= 2;
2838 st->AfterStationTileSetChange(false, STATION_DOCK);
2840 ClearDockingTilesCheckingNeighbours(tile1);
2841 ClearDockingTilesCheckingNeighbours(tile2);
2843 for (Ship *s : Ship::Iterate()) {
2844 /* Find all ships going to our dock. */
2845 if (s->current_order.GetDestination() != st->index) {
2846 continue;
2849 /* Find ships that are marked as "loading" but are no longer on a
2850 * docking tile. Force them to leave the station (as they were loading
2851 * on the removed dock). */
2852 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2853 s->LeaveStation();
2856 /* If we no longer have a dock, mark the order as invalid and send
2857 * the ship to the next order (or, if there is none, make it
2858 * wander the world). */
2859 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
2860 s->SetDestTile(s->GetOrderStationLocation(st->index));
2865 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2868 #include "table/station_land.h"
2870 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2872 return &_station_display_datas[st][gfx];
2876 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2877 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2878 * is set to the overlay to draw.
2879 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
2880 * @param[in,out] ground Groundsprite to draw.
2881 * @param[out] overlay_offset Overlay to draw.
2882 * @return true if overlay can be drawn.
2884 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2886 bool snow_desert;
2887 switch (*ground) {
2888 case SPR_RAIL_TRACK_X:
2889 case SPR_MONO_TRACK_X:
2890 case SPR_MGLV_TRACK_X:
2891 snow_desert = false;
2892 *overlay_offset = RTO_X;
2893 break;
2895 case SPR_RAIL_TRACK_Y:
2896 case SPR_MONO_TRACK_Y:
2897 case SPR_MGLV_TRACK_Y:
2898 snow_desert = false;
2899 *overlay_offset = RTO_Y;
2900 break;
2902 case SPR_RAIL_TRACK_X_SNOW:
2903 case SPR_MONO_TRACK_X_SNOW:
2904 case SPR_MGLV_TRACK_X_SNOW:
2905 snow_desert = true;
2906 *overlay_offset = RTO_X;
2907 break;
2909 case SPR_RAIL_TRACK_Y_SNOW:
2910 case SPR_MONO_TRACK_Y_SNOW:
2911 case SPR_MGLV_TRACK_Y_SNOW:
2912 snow_desert = true;
2913 *overlay_offset = RTO_Y;
2914 break;
2916 default:
2917 return false;
2920 if (ti != nullptr) {
2921 /* Decide snow/desert from tile */
2922 switch (_settings_game.game_creation.landscape) {
2923 case LT_ARCTIC:
2924 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2925 break;
2927 case LT_TROPIC:
2928 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2929 break;
2931 default:
2932 break;
2936 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2937 return true;
2940 static void DrawTile_Station(TileInfo *ti)
2942 const NewGRFSpriteLayout *layout = nullptr;
2943 DrawTileSprites tmp_rail_layout;
2944 const DrawTileSprites *t = nullptr;
2945 int32_t total_offset;
2946 const RailTypeInfo *rti = nullptr;
2947 uint32_t relocation = 0;
2948 uint32_t ground_relocation = 0;
2949 BaseStation *st = nullptr;
2950 const StationSpec *statspec = nullptr;
2951 uint tile_layout = 0;
2953 if (HasStationRail(ti->tile)) {
2954 rti = GetRailTypeInfo(GetRailType(ti->tile));
2955 total_offset = rti->GetRailtypeSpriteOffset();
2957 if (IsCustomStationSpecIndex(ti->tile)) {
2958 /* look for customization */
2959 st = BaseStation::GetByTile(ti->tile);
2960 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2962 if (statspec != nullptr) {
2963 tile_layout = GetStationGfx(ti->tile);
2965 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2966 uint16_t callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2967 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2970 /* Ensure the chosen tile layout is valid for this custom station */
2971 if (!statspec->renderdata.empty()) {
2972 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2973 if (!layout->NeedsPreprocessing()) {
2974 t = layout;
2975 layout = nullptr;
2980 } else {
2981 total_offset = 0;
2984 StationGfx gfx = GetStationGfx(ti->tile);
2985 if (IsAirport(ti->tile)) {
2986 gfx = GetAirportGfx(ti->tile);
2987 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2988 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2989 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
2990 return;
2992 /* No sprite group (or no valid one) found, meaning no graphics associated.
2993 * Use the substitute one instead */
2994 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2995 gfx = ats->grf_prop.subst_id;
2997 switch (gfx) {
2998 case APT_RADAR_GRASS_FENCE_SW:
2999 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3000 break;
3001 case APT_GRASS_FENCE_NE_FLAG:
3002 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3003 break;
3004 case APT_RADAR_FENCE_SW:
3005 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3006 break;
3007 case APT_RADAR_FENCE_NE:
3008 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3009 break;
3010 case APT_GRASS_FENCE_NE_FLAG_2:
3011 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3012 break;
3016 Owner owner = GetTileOwner(ti->tile);
3018 PaletteID palette;
3019 if (Company::IsValidID(owner)) {
3020 palette = COMPANY_SPRITE_COLOUR(owner);
3021 } else {
3022 /* Some stations are not owner by a company, namely oil rigs */
3023 palette = PALETTE_TO_GREY;
3026 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3028 /* don't show foundation for docks */
3029 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3030 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3031 /* Station has custom foundations.
3032 * Check whether the foundation continues beyond the tile's upper sides. */
3033 uint edge_info = 0;
3034 int z;
3035 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
3036 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3037 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3038 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3039 if (image == 0) goto draw_default_foundation;
3041 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3042 /* Station provides extended foundations. */
3044 static const uint8_t foundation_parts[] = {
3045 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3046 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3047 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3048 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3051 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3052 } else {
3053 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3055 /* Each set bit represents one of the eight composite sprites to be drawn.
3056 * 'Invalid' entries will not drawn but are included for completeness. */
3057 static const uint8_t composite_foundation_parts[] = {
3058 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3059 0x00, 0xD1, 0xE4, 0xE0,
3060 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3061 0xCA, 0xC9, 0xC4, 0xC0,
3062 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3063 0xD2, 0x91, 0xE4, 0xA0,
3064 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3065 0x4A, 0x09, 0x44
3068 uint8_t parts = composite_foundation_parts[ti->tileh];
3070 /* If foundations continue beyond the tile's upper sides then
3071 * mask out the last two pieces. */
3072 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3073 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3075 if (parts == 0) {
3076 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3077 * correct offset for the childsprites.
3078 * So, draw the (completely empty) sprite of the default foundations. */
3079 goto draw_default_foundation;
3082 StartSpriteCombine();
3083 for (int i = 0; i < 8; i++) {
3084 if (HasBit(parts, i)) {
3085 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3088 EndSpriteCombine();
3091 OffsetGroundSprite(0, -8);
3092 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
3093 } else {
3094 draw_default_foundation:
3095 DrawFoundation(ti, FOUNDATION_LEVELED);
3099 bool draw_ground = false;
3101 if (IsBuoy(ti->tile)) {
3102 DrawWaterClassGround(ti);
3103 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3104 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3105 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3106 if (ti->tileh == SLOPE_FLAT) {
3107 DrawWaterClassGround(ti);
3108 } else {
3109 assert(IsDock(ti->tile));
3110 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3111 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3112 if (wc == WATER_CLASS_SEA) {
3113 DrawShoreTile(ti->tileh);
3114 } else {
3115 DrawClearLandTile(ti, 3);
3118 } else {
3119 if (layout != nullptr) {
3120 /* Sprite layout which needs preprocessing */
3121 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3122 uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3123 for (uint8_t var10 : SetBitIterator(var10_values)) {
3124 uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3125 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3127 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3128 t = &tmp_rail_layout;
3129 total_offset = 0;
3130 } else if (statspec != nullptr) {
3131 /* Simple sprite layout */
3132 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3133 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3134 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3136 ground_relocation += rti->fallback_railtype;
3139 draw_ground = true;
3142 if (draw_ground && !IsRoadStop(ti->tile)) {
3143 SpriteID image = t->ground.sprite;
3144 PaletteID pal = t->ground.pal;
3145 RailTrackOffset overlay_offset;
3146 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3147 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3148 DrawGroundSprite(image, PAL_NONE);
3149 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3151 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3152 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3153 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3155 } else {
3156 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3157 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3158 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3160 /* PBS debugging, draw reserved tracks darker */
3161 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3162 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3167 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3169 if (IsRoadStop(ti->tile)) {
3170 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3171 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3172 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3173 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3175 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3176 DiagDirection dir = GetRoadStopDir(ti->tile);
3177 StationType type = GetStationType(ti->tile);
3179 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3180 if (stopspec != nullptr) {
3181 int view = dir;
3182 if (IsDriveThroughStopTile(ti->tile)) view += 4;
3183 st = BaseStation::GetByTile(ti->tile);
3184 RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3185 const SpriteGroup *group = object.Resolve();
3186 if (group != nullptr && group->type == SGT_TILELAYOUT) {
3187 t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3191 /* Draw ground sprite */
3192 if (draw_ground) {
3193 SpriteID image = t->ground.sprite;
3194 PaletteID pal = t->ground.pal;
3195 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3196 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3197 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3198 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3202 if (IsDriveThroughStopTile(ti->tile)) {
3203 uint sprite_offset = axis == AXIS_X ? 1 : 0;
3205 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3206 } else {
3207 /* Non-drivethrough road stops are only valid for roads. */
3208 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3210 if ((stopspec == nullptr || (stopspec->draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3211 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3212 DrawGroundSprite(ground + dir, PAL_NONE);
3216 if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3217 /* Draw road, tram catenary */
3218 DrawRoadCatenary(ti);
3222 if (IsRailWaypoint(ti->tile)) {
3223 /* Don't offset the waypoint graphics; they're always the same. */
3224 total_offset = 0;
3227 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3230 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3232 int32_t total_offset = 0;
3233 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3234 const DrawTileSprites *t = GetStationTileLayout(st, image);
3235 const RailTypeInfo *railtype_info = nullptr;
3237 if (railtype != INVALID_RAILTYPE) {
3238 railtype_info = GetRailTypeInfo(railtype);
3239 total_offset = railtype_info->GetRailtypeSpriteOffset();
3242 SpriteID img = t->ground.sprite;
3243 RailTrackOffset overlay_offset;
3244 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3245 SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3246 DrawSprite(img, PAL_NONE, x, y);
3247 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3248 } else {
3249 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3252 if (roadtype != INVALID_ROADTYPE) {
3253 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3254 if (image >= 4) {
3255 /* Drive-through stop */
3256 uint sprite_offset = 5 - image;
3258 /* Road underlay takes precedence over tram */
3259 if (roadtype_info->UsesOverlay()) {
3260 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3261 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3263 SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3264 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3265 } else if (RoadTypeIsTram(roadtype)) {
3266 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3268 } else {
3269 /* Bay stop */
3270 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3271 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3272 DrawSprite(ground + image, PAL_NONE, x, y);
3277 /* Default waypoint has no railtype specific sprites */
3278 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
3281 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3283 return GetTileMaxPixelZ(tile);
3286 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3288 return FlatteningFoundation(tileh);
3291 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3293 RoadType road_rt = GetRoadTypeRoad(tile);
3294 RoadType tram_rt = GetRoadTypeTram(tile);
3295 Owner road_owner = INVALID_OWNER;
3296 Owner tram_owner = INVALID_OWNER;
3297 if (road_rt != INVALID_ROADTYPE) {
3298 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3299 td->roadtype = rti->strings.name;
3300 td->road_speed = rti->max_speed / 2;
3301 road_owner = GetRoadOwner(tile, RTT_ROAD);
3304 if (tram_rt != INVALID_ROADTYPE) {
3305 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3306 td->tramtype = rti->strings.name;
3307 td->tram_speed = rti->max_speed / 2;
3308 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3311 if (IsDriveThroughStopTile(tile)) {
3312 /* Is there a mix of owners? */
3313 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3314 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3315 uint i = 1;
3316 if (road_owner != INVALID_OWNER) {
3317 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3318 td->owner[i] = road_owner;
3319 i++;
3321 if (tram_owner != INVALID_OWNER) {
3322 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3323 td->owner[i] = tram_owner;
3329 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3331 const StationSpec *spec = GetStationSpec(tile);
3333 if (spec != nullptr) {
3334 td->station_class = StationClass::Get(spec->cls_id)->name;
3335 td->station_name = spec->name;
3337 if (spec->grf_prop.grffile != nullptr) {
3338 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3339 td->grf = gc->GetName();
3343 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3344 td->rail_speed = rti->max_speed;
3345 td->railtype = rti->strings.name;
3348 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3350 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3351 td->airport_class = AirportClass::Get(as->cls_id)->name;
3352 td->airport_name = as->name;
3354 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3355 td->airport_tile_name = ats->name;
3357 if (as->grf_prop.grffile != nullptr) {
3358 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3359 td->grf = gc->GetName();
3360 } else if (ats->grf_prop.grffile != nullptr) {
3361 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3362 td->grf = gc->GetName();
3366 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3368 td->owner[0] = GetTileOwner(tile);
3369 td->build_date = BaseStation::GetByTile(tile)->build_date;
3371 if (IsRoadStop(tile)) FillTileDescRoadStop(tile, td);
3372 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3373 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3375 StringID str;
3376 switch (GetStationType(tile)) {
3377 default: NOT_REACHED();
3378 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3379 case STATION_AIRPORT:
3380 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3381 break;
3382 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3383 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3384 case STATION_OILRIG: {
3385 const Industry *i = Station::GetByTile(tile)->industry;
3386 const IndustrySpec *is = GetIndustrySpec(i->type);
3387 td->owner[0] = i->owner;
3388 str = is->name;
3389 if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3390 break;
3392 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3393 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3394 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3396 td->str = str;
3400 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3402 TrackBits trackbits = TRACK_BIT_NONE;
3404 switch (mode) {
3405 case TRANSPORT_RAIL:
3406 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3407 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3409 break;
3411 case TRANSPORT_WATER:
3412 /* buoy is coded as a station, it is always on open water */
3413 if (IsBuoy(tile)) {
3414 trackbits = TRACK_BIT_ALL;
3415 /* remove tracks that connect NE map edge */
3416 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3417 /* remove tracks that connect NW map edge */
3418 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3420 break;
3422 case TRANSPORT_ROAD:
3423 if (IsRoadStop(tile)) {
3424 RoadTramType rtt = (RoadTramType)sub_mode;
3425 if (!HasTileRoadType(tile, rtt)) break;
3427 DiagDirection dir = GetRoadStopDir(tile);
3428 Axis axis = DiagDirToAxis(dir);
3430 if (side != INVALID_DIAGDIR) {
3431 if (axis != DiagDirToAxis(side) || (IsBayRoadStopTile(tile) && dir != side)) break;
3434 trackbits = AxisToTrackBits(axis);
3436 break;
3438 default:
3439 break;
3442 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3446 static void TileLoop_Station(TileIndex tile)
3448 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3449 * hardcoded.....not good */
3450 switch (GetStationType(tile)) {
3451 case STATION_AIRPORT:
3452 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3453 break;
3455 case STATION_DOCK:
3456 if (!IsTileFlat(tile)) break; // only handle water part
3457 [[fallthrough]];
3459 case STATION_OILRIG: //(station part)
3460 case STATION_BUOY:
3461 TileLoop_Water(tile);
3462 break;
3464 default: break;
3469 static void AnimateTile_Station(TileIndex tile)
3471 if (HasStationRail(tile)) {
3472 AnimateStationTile(tile);
3473 return;
3476 if (IsAirport(tile)) {
3477 AnimateAirportTile(tile);
3478 return;
3481 if (IsRoadStopTile(tile)) {
3482 AnimateRoadStopTile(tile);
3483 return;
3488 static bool ClickTile_Station(TileIndex tile)
3490 const BaseStation *bst = BaseStation::GetByTile(tile);
3492 if (bst->facilities & FACIL_WAYPOINT) {
3493 ShowWaypointWindow(Waypoint::From(bst));
3494 } else if (IsHangar(tile)) {
3495 const Station *st = Station::From(bst);
3496 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3497 } else {
3498 ShowStationViewWindow(bst->index);
3500 return true;
3503 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3505 if (v->type == VEH_TRAIN) {
3506 StationID station_id = GetStationIndex(tile);
3507 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3508 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3510 int station_ahead;
3511 int station_length;
3512 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3514 /* Stop whenever that amount of station ahead + the distance from the
3515 * begin of the platform to the stop location is longer than the length
3516 * of the platform. Station ahead 'includes' the current tile where the
3517 * vehicle is on, so we need to subtract that. */
3518 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3520 DiagDirection dir = DirToDiagDir(v->direction);
3522 x &= 0xF;
3523 y &= 0xF;
3525 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3526 if (y == TILE_SIZE / 2) {
3527 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3528 stop &= TILE_SIZE - 1;
3530 if (x == stop) {
3531 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3532 } else if (x < stop) {
3533 v->vehstatus |= VS_TRAIN_SLOWING;
3534 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3535 if (spd < v->cur_speed) v->cur_speed = spd;
3538 } else if (v->type == VEH_ROAD) {
3539 RoadVehicle *rv = RoadVehicle::From(v);
3540 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3541 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3542 /* Attempt to allocate a parking bay in a road stop */
3543 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3548 return VETSB_CONTINUE;
3552 * Run the watched cargo callback for all houses in the catchment area.
3553 * @param st Station.
3555 void TriggerWatchedCargoCallbacks(Station *st)
3557 /* Collect cargoes accepted since the last big tick. */
3558 CargoTypes cargoes = 0;
3559 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3560 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3563 /* Anything to do? */
3564 if (cargoes == 0) return;
3566 /* Loop over all houses in the catchment. */
3567 BitmapTileIterator it(st->catchment_tiles);
3568 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3569 if (IsTileType(tile, MP_HOUSE)) {
3570 WatchedCargoCallback(tile, cargoes);
3576 * This function is called for each station once every 250 ticks.
3577 * Not all stations will get the tick at the same time.
3578 * @param st the station receiving the tick.
3579 * @return true if the station is still valid (wasn't deleted)
3581 static bool StationHandleBigTick(BaseStation *st)
3583 if (!st->IsInUse()) {
3584 if (++st->delete_ctr >= 8) delete st;
3585 return false;
3588 if (Station::IsExpected(st)) {
3589 TriggerWatchedCargoCallbacks(Station::From(st));
3591 for (GoodsEntry &ge : Station::From(st)->goods) {
3592 ClrBit(ge.status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3597 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3599 return true;
3602 static inline void byte_inc_sat(byte *p)
3604 byte b = *p + 1;
3605 if (b != 0) *p = b;
3609 * Truncate the cargo by a specific amount.
3610 * @param cs The type of cargo to perform the truncation for.
3611 * @param ge The goods entry, of the station, to truncate.
3612 * @param amount The amount to truncate the cargo by.
3614 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3616 /* If truncating also punish the source stations' ratings to
3617 * decrease the flow of incoming cargo. */
3619 StationCargoAmountMap waiting_per_source;
3620 ge->cargo.Truncate(amount, &waiting_per_source);
3621 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3622 Station *source_station = Station::GetIfValid(i->first);
3623 if (source_station == nullptr) continue;
3625 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3626 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3630 static void UpdateStationRating(Station *st)
3632 bool waiting_changed = false;
3634 byte_inc_sat(&st->time_since_load);
3635 byte_inc_sat(&st->time_since_unload);
3637 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3638 GoodsEntry *ge = &st->goods[cs->Index()];
3639 /* Slowly increase the rating back to its original level in the case we
3640 * didn't deliver cargo yet to this station. This happens when a bribe
3641 * failed while you didn't moved that cargo yet to a station. */
3642 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3643 ge->rating++;
3646 /* Only change the rating if we are moving this cargo */
3647 if (ge->HasRating()) {
3648 byte_inc_sat(&ge->time_since_pickup);
3649 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3650 ClrBit(ge->status, GoodsEntry::GES_RATING);
3651 ge->last_speed = 0;
3652 TruncateCargo(cs, ge);
3653 waiting_changed = true;
3654 continue;
3657 bool skip = false;
3658 int rating = 0;
3659 uint waiting = ge->cargo.AvailableCount();
3661 /* num_dests is at least 1 if there is any cargo as
3662 * INVALID_STATION is also a destination.
3664 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3666 /* Average amount of cargo per next hop, but prefer solitary stations
3667 * with only one or two next hops. They are allowed to have more
3668 * cargo waiting per next hop.
3669 * With manual cargo distribution waiting_avg = waiting / 2 as then
3670 * INVALID_STATION is the only destination.
3672 uint waiting_avg = waiting / (num_dests + 1);
3674 if (_cheats.station_rating.value) {
3675 ge->rating = rating = MAX_STATION_RATING;
3676 skip = true;
3677 } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3678 /* Perform custom station rating. If it succeeds the speed, days in transit and
3679 * waiting cargo ratings must not be executed. */
3681 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3682 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3684 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3685 | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3686 | (ClampTo<uint8_t>(last_speed) << 24);
3687 /* Convert to the 'old' vehicle types */
3688 uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3689 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3690 if (callback != CALLBACK_FAILED) {
3691 skip = true;
3692 rating = GB(callback, 0, 14);
3694 /* Simulate a 15 bit signed value */
3695 if (HasBit(callback, 14)) rating -= 0x4000;
3699 if (!skip) {
3700 int b = ge->last_speed - 85;
3701 if (b >= 0) rating += b >> 2;
3703 byte waittime = ge->time_since_pickup;
3704 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3705 if (waittime <= 21) rating += 25;
3706 if (waittime <= 12) rating += 25;
3707 if (waittime <= 6) rating += 45;
3708 if (waittime <= 3) rating += 35;
3710 rating -= 90;
3711 if (ge->max_waiting_cargo <= 1500) rating += 55;
3712 if (ge->max_waiting_cargo <= 1000) rating += 35;
3713 if (ge->max_waiting_cargo <= 600) rating += 10;
3714 if (ge->max_waiting_cargo <= 300) rating += 20;
3715 if (ge->max_waiting_cargo <= 100) rating += 10;
3718 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3720 byte age = ge->last_age;
3721 if (age < 3) rating += 10;
3722 if (age < 2) rating += 10;
3723 if (age < 1) rating += 13;
3726 int or_ = ge->rating; // old rating
3728 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3729 ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3731 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3732 * remove some random amount of goods from the station */
3733 if (rating <= 64 && waiting_avg >= 100) {
3734 int dec = Random() & 0x1F;
3735 if (waiting_avg < 200) dec &= 7;
3736 waiting -= (dec + 1) * num_dests;
3737 waiting_changed = true;
3740 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3741 if (rating <= 127 && waiting != 0) {
3742 uint32_t r = Random();
3743 if (rating <= (int)GB(r, 0, 7)) {
3744 /* Need to have int, otherwise it will just overflow etc. */
3745 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3746 waiting_changed = true;
3750 /* At some point we really must cap the cargo. Previously this
3751 * was a strict 4095, but now we'll have a less strict, but
3752 * increasingly aggressive truncation of the amount of cargo. */
3753 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3754 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3755 static const uint MAX_WAITING_CARGO = 1 << 15;
3757 if (waiting > WAITING_CARGO_THRESHOLD) {
3758 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3759 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3761 waiting = std::min(waiting, MAX_WAITING_CARGO);
3762 waiting_changed = true;
3765 /* We can't truncate cargo that's already reserved for loading.
3766 * Thus StoredCount() here. */
3767 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3768 /* Feed back the exact own waiting cargo at this station for the
3769 * next rating calculation. */
3770 ge->max_waiting_cargo = 0;
3772 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3773 } else {
3774 /* If the average number per next hop is low, be more forgiving. */
3775 ge->max_waiting_cargo = waiting_avg;
3781 StationID index = st->index;
3782 if (waiting_changed) {
3783 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3784 } else {
3785 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3790 * Reroute cargo of type c at station st or in any vehicles unloading there.
3791 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3792 * @param st Station to be rerouted at.
3793 * @param c Type of cargo.
3794 * @param avoid Original next hop of cargo, avoid this.
3795 * @param avoid2 Another station to be avoided when rerouting.
3797 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3799 GoodsEntry &ge = st->goods[c];
3801 /* Reroute cargo in station. */
3802 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3804 /* Reroute cargo staged to be transferred. */
3805 for (Vehicle *v : st->loading_vehicles) {
3806 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
3807 if (u->cargo_type != c) continue;
3808 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
3814 * Check all next hops of cargo packets in this station for existence of a
3815 * a valid link they may use to travel on. Reroute any cargo not having a valid
3816 * link and remove timed out links found like this from the linkgraph. We're
3817 * not all links here as that is expensive and useless. A link no one is using
3818 * doesn't hurt either.
3819 * @param from Station to check.
3821 void DeleteStaleLinks(Station *from)
3823 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3824 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
3825 GoodsEntry &ge = from->goods[c];
3826 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3827 if (lg == nullptr) continue;
3828 std::vector<NodeID> to_remove{};
3829 for (Edge &edge : (*lg)[ge.node].edges) {
3830 Station *to = Station::Get((*lg)[edge.dest_node].station);
3831 assert(to->goods[c].node == edge.dest_node);
3832 assert(TimerGameEconomy::date >= edge.LastUpdate());
3833 auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
3834 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
3835 bool updated = false;
3837 if (auto_distributed) {
3838 /* Have all vehicles refresh their next hops before deciding to
3839 * remove the node. */
3840 std::vector<Vehicle *> vehicles;
3841 for (OrderList *l : OrderList::Iterate()) {
3842 bool found_from = false;
3843 bool found_to = false;
3844 for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
3845 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3846 if (order->GetDestination() == from->index) {
3847 found_from = true;
3848 if (found_to) break;
3849 } else if (order->GetDestination() == to->index) {
3850 found_to = true;
3851 if (found_from) break;
3854 if (!found_to || !found_from) continue;
3855 vehicles.push_back(l->GetFirstSharedVehicle());
3858 auto iter = vehicles.begin();
3859 while (iter != vehicles.end()) {
3860 Vehicle *v = *iter;
3861 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
3862 if (!v->IsStoppedInDepot() || TimerGameEconomy::date - v->date_of_last_service <= LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
3863 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3865 if (edge.LastUpdate() == TimerGameEconomy::date) {
3866 updated = true;
3867 break;
3870 Vehicle *next_shared = v->NextShared();
3871 if (next_shared) {
3872 *iter = next_shared;
3873 ++iter;
3874 } else {
3875 iter = vehicles.erase(iter);
3878 if (iter == vehicles.end()) iter = vehicles.begin();
3882 if (!updated) {
3883 /* If it's still considered dead remove it. */
3884 to_remove.emplace_back(to->goods[c].node);
3885 ge.flows.DeleteFlows(to->index);
3886 RerouteCargo(from, c, to->index, from->index);
3888 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
3889 edge.Restrict();
3890 ge.flows.RestrictFlows(to->index);
3891 RerouteCargo(from, c, to->index, from->index);
3892 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
3893 edge.Release();
3896 /* Remove dead edges. */
3897 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
3899 assert(TimerGameEconomy::date >= lg->LastCompression());
3900 if (TimerGameEconomy::date - lg->LastCompression() > LinkGraph::COMPRESSION_INTERVAL) {
3901 lg->Compress();
3907 * Increase capacity for a link stat given by station cargo and next hop.
3908 * @param st Station to get the link stats from.
3909 * @param cargo Cargo to increase stat for.
3910 * @param next_station_id Station the consist will be travelling to next.
3911 * @param capacity Capacity to add to link stat.
3912 * @param usage Usage to add to link stat.
3913 * @param mode Update mode to be applied.
3915 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
3917 GoodsEntry &ge1 = st->goods[cargo];
3918 Station *st2 = Station::Get(next_station_id);
3919 GoodsEntry &ge2 = st2->goods[cargo];
3920 LinkGraph *lg = nullptr;
3921 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3922 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3923 if (LinkGraph::CanAllocateItem()) {
3924 lg = new LinkGraph(cargo);
3925 LinkGraphSchedule::instance.Queue(lg);
3926 ge2.link_graph = lg->index;
3927 ge2.node = lg->AddNode(st2);
3928 } else {
3929 Debug(misc, 0, "Can't allocate link graph");
3931 } else {
3932 lg = LinkGraph::Get(ge2.link_graph);
3934 if (lg) {
3935 ge1.link_graph = lg->index;
3936 ge1.node = lg->AddNode(st);
3938 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3939 lg = LinkGraph::Get(ge1.link_graph);
3940 ge2.link_graph = lg->index;
3941 ge2.node = lg->AddNode(st2);
3942 } else {
3943 lg = LinkGraph::Get(ge1.link_graph);
3944 if (ge1.link_graph != ge2.link_graph) {
3945 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3946 if (lg->Size() < lg2->Size()) {
3947 LinkGraphSchedule::instance.Unqueue(lg);
3948 lg2->Merge(lg); // Updates GoodsEntries of lg
3949 lg = lg2;
3950 } else {
3951 LinkGraphSchedule::instance.Unqueue(lg2);
3952 lg->Merge(lg2); // Updates GoodsEntries of lg2
3956 if (lg != nullptr) {
3957 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
3962 * Increase capacity for all link stats associated with vehicles in the given consist.
3963 * @param st Station to get the link stats from.
3964 * @param front First vehicle in the consist.
3965 * @param next_station_id Station the consist will be travelling to next.
3967 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
3969 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
3970 if (v->refit_cap > 0) {
3971 /* The cargo count can indeed be higher than the refit_cap if
3972 * wagons have been auto-replaced and subsequently auto-
3973 * refitted to a higher capacity. The cargo gets redistributed
3974 * among the wagons in that case.
3975 * As usage is not such an important figure anyway we just
3976 * ignore the additional cargo then.*/
3977 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3978 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
3983 /* called for every station each tick */
3984 static void StationHandleSmallTick(BaseStation *st)
3986 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3988 byte b = st->delete_ctr + 1;
3989 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
3990 st->delete_ctr = b;
3992 if (b == 0) UpdateStationRating(Station::From(st));
3995 void OnTick_Station()
3997 if (_game_mode == GM_EDITOR) return;
3999 for (BaseStation *st : BaseStation::Iterate()) {
4000 StationHandleSmallTick(st);
4002 /* Clean up the link graph about once a week. */
4003 if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % Ticks::STATION_LINKGRAPH_TICKS == 0) {
4004 DeleteStaleLinks(Station::From(st));
4007 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4008 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4009 /* Stop processing this station if it was deleted */
4010 if (!StationHandleBigTick(st)) continue;
4013 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4014 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4015 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4016 TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4017 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4022 /** Economy monthly loop for stations. */
4023 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4025 for (Station *st : Station::Iterate()) {
4026 for (GoodsEntry &ge : st->goods) {
4027 SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));
4028 ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);
4033 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4035 ForAllStationsRadius(tile, radius, [&](Station *st) {
4036 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4037 for (GoodsEntry &ge : st->goods) {
4038 if (ge.status != 0) {
4039 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4046 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4048 /* We can't allocate a CargoPacket? Then don't do anything
4049 * at all; i.e. just discard the incoming cargo. */
4050 if (!CargoPacket::CanAllocateItem()) return 0;
4052 GoodsEntry &ge = st->goods[type];
4053 amount += ge.amount_fract;
4054 ge.amount_fract = GB(amount, 0, 8);
4056 amount >>= 8;
4057 /* No new "real" cargo item yet. */
4058 if (amount == 0) return 0;
4060 StationID next = ge.GetVia(st->index);
4061 ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4062 LinkGraph *lg = nullptr;
4063 if (ge.link_graph == INVALID_LINK_GRAPH) {
4064 if (LinkGraph::CanAllocateItem()) {
4065 lg = new LinkGraph(type);
4066 LinkGraphSchedule::instance.Queue(lg);
4067 ge.link_graph = lg->index;
4068 ge.node = lg->AddNode(st);
4069 } else {
4070 Debug(misc, 0, "Can't allocate link graph");
4072 } else {
4073 lg = LinkGraph::Get(ge.link_graph);
4075 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4077 if (!ge.HasRating()) {
4078 InvalidateWindowData(WC_STATION_LIST, st->owner);
4079 SetBit(ge.status, GoodsEntry::GES_RATING);
4082 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
4083 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4084 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4085 TriggerRoadStopRandomisation(st, st->xy, RSRT_NEW_CARGO, type);
4086 TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4089 SetWindowDirty(WC_STATION_VIEW, st->index);
4090 st->MarkTilesDirty(true);
4091 return amount;
4094 static bool IsUniqueStationName(const std::string &name)
4096 for (const Station *st : Station::Iterate()) {
4097 if (!st->name.empty() && st->name == name) return false;
4100 return true;
4104 * Rename a station
4105 * @param flags operation to perform
4106 * @param station_id station ID that is to be renamed
4107 * @param text the new name or an empty string when resetting to the default
4108 * @return the cost of this operation or an error
4110 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4112 Station *st = Station::GetIfValid(station_id);
4113 if (st == nullptr) return CMD_ERROR;
4115 CommandCost ret = CheckOwnership(st->owner);
4116 if (ret.Failed()) return ret;
4118 bool reset = text.empty();
4120 if (!reset) {
4121 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
4122 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
4125 if (flags & DC_EXEC) {
4126 st->cached_name.clear();
4127 if (reset) {
4128 st->name.clear();
4129 } else {
4130 st->name = text;
4133 st->UpdateVirtCoord();
4134 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4137 return CommandCost();
4140 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
4142 for (Station *st : nearby) {
4143 if (st->TileIsInCatchment(tile)) stations->insert(st);
4148 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4149 * @return pointer to a StationList containing all stations found
4151 const StationList *StationFinder::GetStations()
4153 if (this->tile != INVALID_TILE) {
4154 if (IsTileType(this->tile, MP_HOUSE)) {
4155 /* Town nearby stations need to be filtered per tile. */
4156 assert(this->w == 1 && this->h == 1);
4157 AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
4158 } else {
4159 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4160 this->stations.insert(st);
4161 return true;
4164 this->tile = INVALID_TILE;
4166 return &this->stations;
4170 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4172 /* Is the station reserved exclusively for somebody else? */
4173 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4175 /* Lowest possible rating, better not to give cargo anymore. */
4176 if (st->goods[type].rating == 0) return false;
4178 /* Selectively servicing stations, and not this one. */
4179 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4181 if (IsCargoInClass(type, CC_PASSENGERS)) {
4182 /* Passengers are never served by just a truck stop. */
4183 if (st->facilities == FACIL_TRUCK_STOP) return false;
4184 } else {
4185 /* Non-passengers are never served by just a bus stop. */
4186 if (st->facilities == FACIL_BUS_STOP) return false;
4188 return true;
4191 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4193 /* Return if nothing to do. Also the rounding below fails for 0. */
4194 if (all_stations->empty()) return 0;
4195 if (amount == 0) return 0;
4197 Station *first_station = nullptr;
4198 typedef std::pair<Station *, uint> StationInfo;
4199 std::vector<StationInfo> used_stations;
4201 for (Station *st : *all_stations) {
4202 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4203 if (!CanMoveGoodsToStation(st, type)) continue;
4205 /* Avoid allocating a vector if there is only one station to significantly
4206 * improve performance in this common case. */
4207 if (first_station == nullptr) {
4208 first_station = st;
4209 continue;
4211 if (used_stations.empty()) {
4212 used_stations.reserve(2);
4213 used_stations.emplace_back(std::make_pair(first_station, 0));
4215 used_stations.emplace_back(std::make_pair(st, 0));
4218 /* no stations around at all? */
4219 if (first_station == nullptr) return 0;
4221 if (used_stations.empty()) {
4222 /* only one station around */
4223 amount *= first_station->goods[type].rating + 1;
4224 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4227 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4228 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4229 uint best_rating = 0;
4230 uint best_sum = 0; // sum of best ratings for each company
4232 for (auto &p : used_stations) {
4233 auto owner = p.first->owner;
4234 auto rating = p.first->goods[type].rating;
4235 if (rating > company_best[owner]) {
4236 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4237 company_best[owner] = rating;
4238 if (rating > best_rating) best_rating = rating;
4240 company_sum[owner] += rating;
4243 /* From now we'll calculate with fractional cargo amounts.
4244 * First determine how much cargo we really have. */
4245 amount *= best_rating + 1;
4247 uint moving = 0;
4248 for (auto &p : used_stations) {
4249 uint owner = p.first->owner;
4250 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4251 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4252 p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4253 moving += p.second;
4256 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4257 if (amount > moving) {
4258 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4259 return b.first->goods[type].rating < a.first->goods[type].rating;
4262 assert(amount - moving <= used_stations.size());
4263 for (uint i = 0; i < amount - moving; i++) {
4264 used_stations[i].second++;
4268 uint moved = 0;
4269 for (auto &p : used_stations) {
4270 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4273 return moved;
4276 void UpdateStationDockingTiles(Station *st)
4278 st->docking_station.Clear();
4280 /* For neutral stations, start with the industry area instead of dock area */
4281 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4283 if (area->tile == INVALID_TILE) return;
4285 int x = TileX(area->tile);
4286 int y = TileY(area->tile);
4288 /* Expand the area by a tile on each side while
4289 * making sure that we remain inside the map. */
4290 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4291 int x1 = std::max<int>(x - 1, 0);
4293 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4294 int y1 = std::max<int>(y - 1, 0);
4296 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4297 for (TileIndex tile : ta) {
4298 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4302 void BuildOilRig(TileIndex tile)
4304 if (!Station::CanAllocateItem()) {
4305 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4306 return;
4309 Station *st = new Station(tile);
4310 _station_kdtree.Insert(st->index);
4311 st->town = ClosestTownFromTile(tile, UINT_MAX);
4313 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4315 assert(IsTileType(tile, MP_INDUSTRY));
4316 /* Mark industry as associated both ways */
4317 st->industry = Industry::GetByTile(tile);
4318 st->industry->neutral_station = st;
4319 DeleteAnimatedTile(tile);
4320 MakeOilrig(tile, st->index, GetWaterClass(tile));
4322 st->owner = OWNER_NONE;
4323 st->airport.type = AT_OILRIG;
4324 st->airport.Add(tile);
4325 st->ship_station.Add(tile);
4326 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4327 st->build_date = TimerGameCalendar::date;
4328 UpdateStationDockingTiles(st);
4330 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4332 st->UpdateVirtCoord();
4333 st->RecomputeCatchment();
4334 UpdateStationAcceptance(st, false);
4337 void DeleteOilRig(TileIndex tile)
4339 Station *st = Station::GetByTile(tile);
4341 MakeWaterKeepingClass(tile, OWNER_NONE);
4343 /* The oil rig station is not supposed to be shared with anything else */
4344 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4345 if (st->industry != nullptr && st->industry->neutral_station == st) {
4346 /* Don't leave dangling neutral station pointer */
4347 st->industry->neutral_station = nullptr;
4349 delete st;
4352 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4354 if (IsRoadStopTile(tile)) {
4355 for (RoadTramType rtt : _roadtramtypes) {
4356 /* Update all roadtypes, no matter if they are present */
4357 if (GetRoadOwner(tile, rtt) == old_owner) {
4358 RoadType rt = GetRoadType(tile, rtt);
4359 if (rt != INVALID_ROADTYPE) {
4360 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4361 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4362 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4364 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4369 if (!IsTileOwner(tile, old_owner)) return;
4371 if (new_owner != INVALID_OWNER) {
4372 /* Update company infrastructure counts. Only do it here
4373 * if the new owner is valid as otherwise the clear
4374 * command will do it for us. No need to dirty windows
4375 * here, we'll redraw the whole screen anyway.*/
4376 Company *old_company = Company::Get(old_owner);
4377 Company *new_company = Company::Get(new_owner);
4379 /* Update counts for underlying infrastructure. */
4380 switch (GetStationType(tile)) {
4381 case STATION_RAIL:
4382 case STATION_WAYPOINT:
4383 if (!IsStationTileBlocked(tile)) {
4384 old_company->infrastructure.rail[GetRailType(tile)]--;
4385 new_company->infrastructure.rail[GetRailType(tile)]++;
4387 break;
4389 case STATION_BUS:
4390 case STATION_TRUCK:
4391 /* Road stops were already handled above. */
4392 break;
4394 case STATION_BUOY:
4395 case STATION_DOCK:
4396 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4397 old_company->infrastructure.water--;
4398 new_company->infrastructure.water++;
4400 break;
4402 default:
4403 break;
4406 /* Update station tile count. */
4407 if (!IsBuoy(tile) && !IsAirport(tile)) {
4408 old_company->infrastructure.station--;
4409 new_company->infrastructure.station++;
4412 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4413 SetTileOwner(tile, new_owner);
4414 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4415 } else {
4416 if (IsDriveThroughStopTile(tile)) {
4417 /* Remove the drive-through road stop */
4418 Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4419 assert(IsTileType(tile, MP_ROAD));
4420 /* Change owner of tile and all roadtypes */
4421 ChangeTileOwner(tile, old_owner, new_owner);
4422 } else {
4423 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
4424 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4425 * Update owner of buoy if it was not removed (was in orders).
4426 * Do not update when owned by OWNER_WATER (sea and rivers). */
4427 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4433 * Check if a drive-through road stop tile can be cleared.
4434 * Road stops built on town-owned roads check the conditions
4435 * that would allow clearing of the original road.
4436 * @param tile road stop tile to check
4437 * @param flags command flags
4438 * @return true if the road can be cleared
4440 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4442 /* Yeah... water can always remove stops, right? */
4443 if (_current_company == OWNER_WATER) return true;
4445 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4446 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4447 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4449 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4450 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4451 if (road_owner != OWNER_TOWN) {
4452 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4453 } else {
4454 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags).Failed()) return false;
4458 return true;
4462 * Clear a single tile of a station.
4463 * @param tile The tile to clear.
4464 * @param flags The DoCommand flags related to the "command".
4465 * @return The cost, or error of clearing.
4467 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4469 if (flags & DC_AUTO) {
4470 switch (GetStationType(tile)) {
4471 default: break;
4472 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4473 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4474 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4475 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);
4476 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);
4477 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4478 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4479 case STATION_OILRIG:
4480 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4481 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4485 switch (GetStationType(tile)) {
4486 case STATION_RAIL: return RemoveRailStation(tile, flags);
4487 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4488 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4489 case STATION_TRUCK:
4490 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4491 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4493 return RemoveRoadStop(tile, flags);
4494 case STATION_BUS:
4495 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4496 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4498 return RemoveRoadStop(tile, flags);
4499 case STATION_BUOY: return RemoveBuoy(tile, flags);
4500 case STATION_DOCK: return RemoveDock(tile, flags);
4501 default: break;
4504 return CMD_ERROR;
4507 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4509 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4510 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4511 * TTDP does not call it.
4513 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4514 switch (GetStationType(tile)) {
4515 case STATION_WAYPOINT:
4516 case STATION_RAIL: {
4517 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4518 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4519 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4520 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4523 case STATION_AIRPORT:
4524 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4526 case STATION_TRUCK:
4527 case STATION_BUS: {
4528 DiagDirection direction = GetRoadStopDir(tile);
4529 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4530 if (IsDriveThroughStopTile(tile)) {
4531 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4533 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4536 default: break;
4540 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4544 * Get flow for a station.
4545 * @param st Station to get flow for.
4546 * @return Flow for st.
4548 uint FlowStat::GetShare(StationID st) const
4550 uint32_t prev = 0;
4551 for (const auto &it : this->shares) {
4552 if (it.second == st) {
4553 return it.first - prev;
4554 } else {
4555 prev = it.first;
4558 return 0;
4562 * Get a station a package can be routed to, but exclude the given ones.
4563 * @param excluded StationID not to be selected.
4564 * @param excluded2 Another StationID not to be selected.
4565 * @return A station ID from the shares map.
4567 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4569 if (this->unrestricted == 0) return INVALID_STATION;
4570 assert(!this->shares.empty());
4571 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4572 assert(it != this->shares.end() && it->first <= this->unrestricted);
4573 if (it->second != excluded && it->second != excluded2) return it->second;
4575 /* We've hit one of the excluded stations.
4576 * Draw another share, from outside its range. */
4578 uint end = it->first;
4579 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4580 uint interval = end - begin;
4581 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4582 uint new_max = this->unrestricted - interval;
4583 uint rand = RandomRange(new_max);
4584 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4585 this->shares.upper_bound(rand + interval);
4586 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4587 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4589 /* We've hit the second excluded station.
4590 * Same as before, only a bit more complicated. */
4592 uint end2 = it2->first;
4593 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4594 uint interval2 = end2 - begin2;
4595 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4596 new_max -= interval2;
4597 if (begin > begin2) {
4598 Swap(begin, begin2);
4599 Swap(end, end2);
4600 Swap(interval, interval2);
4602 rand = RandomRange(new_max);
4603 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4604 if (rand < begin) {
4605 it3 = this->shares.upper_bound(rand);
4606 } else if (rand < begin2 - interval) {
4607 it3 = this->shares.upper_bound(rand + interval);
4608 } else {
4609 it3 = this->shares.upper_bound(rand + interval + interval2);
4611 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4612 return it3->second;
4616 * Reduce all flows to minimum capacity so that they don't get in the way of
4617 * link usage statistics too much. Keep them around, though, to continue
4618 * routing any remaining cargo.
4620 void FlowStat::Invalidate()
4622 assert(!this->shares.empty());
4623 SharesMap new_shares;
4624 uint i = 0;
4625 for (const auto &it : this->shares) {
4626 new_shares[++i] = it.second;
4627 if (it.first == this->unrestricted) this->unrestricted = i;
4629 this->shares.swap(new_shares);
4630 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4634 * Change share for specified station. By specifying INT_MIN as parameter you
4635 * can erase a share. Newly added flows will be unrestricted.
4636 * @param st Next Hop to be removed.
4637 * @param flow Share to be added or removed.
4639 void FlowStat::ChangeShare(StationID st, int flow)
4641 /* We assert only before changing as afterwards the shares can actually
4642 * be empty. In that case the whole flow stat must be deleted then. */
4643 assert(!this->shares.empty());
4645 uint removed_shares = 0;
4646 uint added_shares = 0;
4647 uint last_share = 0;
4648 SharesMap new_shares;
4649 for (const auto &it : this->shares) {
4650 if (it.second == st) {
4651 if (flow < 0) {
4652 uint share = it.first - last_share;
4653 if (flow == INT_MIN || (uint)(-flow) >= share) {
4654 removed_shares += share;
4655 if (it.first <= this->unrestricted) this->unrestricted -= share;
4656 if (flow != INT_MIN) flow += share;
4657 last_share = it.first;
4658 continue; // remove the whole share
4660 removed_shares += (uint)(-flow);
4661 } else {
4662 added_shares += (uint)(flow);
4664 if (it.first <= this->unrestricted) this->unrestricted += flow;
4666 /* If we don't continue above the whole flow has been added or
4667 * removed. */
4668 flow = 0;
4670 new_shares[it.first + added_shares - removed_shares] = it.second;
4671 last_share = it.first;
4673 if (flow > 0) {
4674 new_shares[last_share + (uint)flow] = st;
4675 if (this->unrestricted < last_share) {
4676 this->ReleaseShare(st);
4677 } else {
4678 this->unrestricted += flow;
4681 this->shares.swap(new_shares);
4685 * Restrict a flow by moving it to the end of the map and decreasing the amount
4686 * of unrestricted flow.
4687 * @param st Station of flow to be restricted.
4689 void FlowStat::RestrictShare(StationID st)
4691 assert(!this->shares.empty());
4692 uint flow = 0;
4693 uint last_share = 0;
4694 SharesMap new_shares;
4695 for (auto &it : this->shares) {
4696 if (flow == 0) {
4697 if (it.first > this->unrestricted) return; // Not present or already restricted.
4698 if (it.second == st) {
4699 flow = it.first - last_share;
4700 this->unrestricted -= flow;
4701 } else {
4702 new_shares[it.first] = it.second;
4704 } else {
4705 new_shares[it.first - flow] = it.second;
4707 last_share = it.first;
4709 if (flow == 0) return;
4710 new_shares[last_share + flow] = st;
4711 this->shares.swap(new_shares);
4712 assert(!this->shares.empty());
4716 * Release ("unrestrict") a flow by moving it to the begin of the map and
4717 * increasing the amount of unrestricted flow.
4718 * @param st Station of flow to be released.
4720 void FlowStat::ReleaseShare(StationID st)
4722 assert(!this->shares.empty());
4723 uint flow = 0;
4724 uint next_share = 0;
4725 bool found = false;
4726 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4727 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4728 if (found) {
4729 flow = next_share - it->first;
4730 this->unrestricted += flow;
4731 break;
4732 } else {
4733 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4734 if (it->second == st) found = true;
4736 next_share = it->first;
4738 if (flow == 0) return;
4739 SharesMap new_shares;
4740 new_shares[flow] = st;
4741 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4742 if (it->second != st) {
4743 new_shares[flow + it->first] = it->second;
4744 } else {
4745 flow = 0;
4748 this->shares.swap(new_shares);
4749 assert(!this->shares.empty());
4753 * Scale all shares from link graph's runtime to monthly values.
4754 * @param runtime Time the link graph has been running without compression.
4755 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4757 void FlowStat::ScaleToMonthly(uint runtime)
4759 assert(runtime > 0);
4760 SharesMap new_shares;
4761 uint share = 0;
4762 for (auto i : this->shares) {
4763 share = std::max(share + 1, i.first * 30 / runtime);
4764 new_shares[share] = i.second;
4765 if (this->unrestricted == i.first) this->unrestricted = share;
4767 this->shares.swap(new_shares);
4771 * Add some flow from "origin", going via "via".
4772 * @param origin Origin of the flow.
4773 * @param via Next hop.
4774 * @param flow Amount of flow to be added.
4776 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4778 FlowStatMap::iterator origin_it = this->find(origin);
4779 if (origin_it == this->end()) {
4780 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4781 } else {
4782 origin_it->second.ChangeShare(via, flow);
4783 assert(!origin_it->second.GetShares()->empty());
4788 * Pass on some flow, remembering it as invalid, for later subtraction from
4789 * locally consumed flow. This is necessary because we can't have negative
4790 * flows and we don't want to sort the flows before adding them up.
4791 * @param origin Origin of the flow.
4792 * @param via Next hop.
4793 * @param flow Amount of flow to be passed.
4795 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4797 FlowStatMap::iterator prev_it = this->find(origin);
4798 if (prev_it == this->end()) {
4799 FlowStat fs(via, flow);
4800 fs.AppendShare(INVALID_STATION, flow);
4801 this->insert(std::make_pair(origin, fs));
4802 } else {
4803 prev_it->second.ChangeShare(via, flow);
4804 prev_it->second.ChangeShare(INVALID_STATION, flow);
4805 assert(!prev_it->second.GetShares()->empty());
4810 * Subtract invalid flows from locally consumed flow.
4811 * @param self ID of own station.
4813 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4815 for (auto &i : *this) {
4816 FlowStat &fs = i.second;
4817 uint local = fs.GetShare(INVALID_STATION);
4818 if (local > INT_MAX) { // make sure it fits in an int
4819 fs.ChangeShare(self, -INT_MAX);
4820 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4821 local -= INT_MAX;
4823 fs.ChangeShare(self, -(int)local);
4824 fs.ChangeShare(INVALID_STATION, -(int)local);
4826 /* If the local share is used up there must be a share for some
4827 * remote station. */
4828 assert(!fs.GetShares()->empty());
4833 * Delete all flows at a station for specific cargo and destination.
4834 * @param via Remote station of flows to be deleted.
4835 * @return IDs of source stations for which the complete FlowStat, not only a
4836 * share, has been erased.
4838 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4840 StationIDStack ret;
4841 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4842 FlowStat &s_flows = f_it->second;
4843 s_flows.ChangeShare(via, INT_MIN);
4844 if (s_flows.GetShares()->empty()) {
4845 ret.Push(f_it->first);
4846 this->erase(f_it++);
4847 } else {
4848 ++f_it;
4851 return ret;
4855 * Restrict all flows at a station for specific cargo and destination.
4856 * @param via Remote station of flows to be restricted.
4858 void FlowStatMap::RestrictFlows(StationID via)
4860 for (auto &it : *this) {
4861 it.second.RestrictShare(via);
4866 * Release all flows at a station for specific cargo and destination.
4867 * @param via Remote station of flows to be released.
4869 void FlowStatMap::ReleaseFlows(StationID via)
4871 for (auto &it : *this) {
4872 it.second.ReleaseShare(via);
4877 * Get the sum of all flows from this FlowStatMap.
4878 * @return sum of all flows.
4880 uint FlowStatMap::GetFlow() const
4882 uint ret = 0;
4883 for (const auto &it : *this) {
4884 ret += (--(it.second.GetShares()->end()))->first;
4886 return ret;
4890 * Get the sum of flows via a specific station from this FlowStatMap.
4891 * @param via Remote station to look for.
4892 * @return all flows for 'via' added up.
4894 uint FlowStatMap::GetFlowVia(StationID via) const
4896 uint ret = 0;
4897 for (const auto &it : *this) {
4898 ret += it.second.GetShare(via);
4900 return ret;
4904 * Get the sum of flows from a specific station from this FlowStatMap.
4905 * @param from Origin station to look for.
4906 * @return all flows from 'from' added up.
4908 uint FlowStatMap::GetFlowFrom(StationID from) const
4910 FlowStatMap::const_iterator i = this->find(from);
4911 if (i == this->end()) return 0;
4912 return (--(i->second.GetShares()->end()))->first;
4916 * Get the flow from a specific station via a specific other station.
4917 * @param from Origin station to look for.
4918 * @param via Remote station to look for.
4919 * @return flow share originating at 'from' and going to 'via'.
4921 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4923 FlowStatMap::const_iterator i = this->find(from);
4924 if (i == this->end()) return 0;
4925 return i->second.GetShare(via);
4928 extern const TileTypeProcs _tile_type_station_procs = {
4929 DrawTile_Station, // draw_tile_proc
4930 GetSlopePixelZ_Station, // get_slope_z_proc
4931 ClearTile_Station, // clear_tile_proc
4932 nullptr, // add_accepted_cargo_proc
4933 GetTileDesc_Station, // get_tile_desc_proc
4934 GetTileTrackStatus_Station, // get_tile_track_status_proc
4935 ClickTile_Station, // click_tile_proc
4936 AnimateTile_Station, // animate_tile_proc
4937 TileLoop_Station, // tile_loop_proc
4938 ChangeTileOwner_Station, // change_tile_owner_proc
4939 nullptr, // add_produced_cargo_proc
4940 VehicleEnter_Station, // vehicle_enter_tile_proc
4941 GetFoundation_Station, // get_foundation_proc
4942 TerraformTile_Station, // terraform_tile_proc