Codechange: Add HasFlag() to test if a value is present in a bitset enum type. (...
[openttd-github.git] / src / station_cmd.cpp
blob855c8ef1d5bf5ce2ba2e478065ba078449f11f51
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 "vehiclelist_func.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "command_func.h"
17 #include "town.h"
18 #include "news_func.h"
19 #include "train.h"
20 #include "ship.h"
21 #include "roadveh.h"
22 #include "industry.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
30 #include "water.h"
31 #include "strings_internal.h"
32 #include "clear_func.h"
33 #include "timer/timer_game_calendar.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "station_func.h"
40 #include "station_kdtree.h"
41 #include "roadstop_base.h"
42 #include "newgrf_railtype.h"
43 #include "newgrf_roadtype.h"
44 #include "waypoint_base.h"
45 #include "waypoint_func.h"
46 #include "pbs.h"
47 #include "debug.h"
48 #include "core/random_func.hpp"
49 #include "core/container_func.hpp"
50 #include "company_base.h"
51 #include "table/airporttile_ids.h"
52 #include "newgrf_airporttiles.h"
53 #include "order_backup.h"
54 #include "newgrf_house.h"
55 #include "company_gui.h"
56 #include "linkgraph/linkgraph_base.h"
57 #include "linkgraph/refresh.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"
69 #include "road_func.h"
71 #include "widgets/station_widget.h"
73 #include "table/strings.h"
75 #include <bitset>
77 #include "safeguards.h"
79 /**
80 * Static instance of FlowStat::SharesMap.
81 * Note: This instance is created on task start.
82 * Lazy creation on first usage results in a data race between the CDist threads.
84 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
86 /**
87 * Check whether the given tile is a hangar.
88 * @param t the tile to of whether it is a hangar.
89 * @pre IsTileType(t, MP_STATION)
90 * @return true if and only if the tile is a hangar.
92 bool IsHangar(Tile t)
94 assert(IsTileType(t, MP_STATION));
96 /* If the tile isn't an airport there's no chance it's a hangar. */
97 if (!IsAirport(t)) return false;
99 const Station *st = Station::GetByTile(t);
100 const AirportSpec *as = st->airport.GetSpec();
102 for (const auto &depot : as->depots) {
103 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
106 return false;
110 * Look for a station owned by the given company around the given tile area.
111 * @param ta the area to search over
112 * @param closest_station the closest owned station found so far
113 * @param company the company whose stations to look for
114 * @param st to 'return' the found station
115 * @param filter Filter function
116 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
118 template <class T, class F>
119 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
121 ta.Expand(1);
123 /* check around to see if there are any stations there owned by the company */
124 for (TileIndex tile_cur : ta) {
125 if (IsTileType(tile_cur, MP_STATION)) {
126 StationID t = GetStationIndex(tile_cur);
127 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
128 if (closest_station == INVALID_STATION) {
129 closest_station = t;
130 } else if (closest_station != t) {
131 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
135 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
136 return CommandCost();
140 * Function to check whether the given tile matches some criterion.
141 * @param tile the tile to check
142 * @return true if it matches, false otherwise
144 typedef bool (*CMSAMatcher)(TileIndex tile);
147 * Counts the numbers of tiles matching a specific type in the area around
148 * @param tile the center tile of the 'count area'
149 * @param cmp the comparator/matcher (@see CMSAMatcher)
150 * @return the number of matching tiles around
152 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
154 int num = 0;
156 for (int dx = -3; dx <= 3; dx++) {
157 for (int dy = -3; dy <= 3; dy++) {
158 TileIndex t = TileAddWrap(tile, dx, dy);
159 if (t != INVALID_TILE && cmp(t)) num++;
163 return num;
167 * Check whether the tile is a mine.
168 * @param tile the tile to investigate.
169 * @return true if and only if the tile is a mine
171 static bool CMSAMine(TileIndex tile)
173 /* No industry */
174 if (!IsTileType(tile, MP_INDUSTRY)) return false;
176 const Industry *ind = Industry::GetByTile(tile);
178 /* No extractive industry */
179 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
181 for (const auto &p : ind->produced) {
182 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
183 * Also the production of passengers and mail is ignored. */
184 if (IsValidCargoID(p.cargo) &&
185 (CargoSpec::Get(p.cargo)->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
186 return true;
190 return false;
194 * Check whether the tile is water.
195 * @param tile the tile to investigate.
196 * @return true if and only if the tile is a water tile
198 static bool CMSAWater(TileIndex tile)
200 return IsTileType(tile, MP_WATER) && IsWater(tile);
204 * Check whether the tile is a tree.
205 * @param tile the tile to investigate.
206 * @return true if and only if the tile is a tree tile
208 static bool CMSATree(TileIndex tile)
210 return IsTileType(tile, MP_TREES);
213 #define M(x) ((x) - STR_SV_STNAME)
215 enum StationNaming {
216 STATIONNAMING_RAIL,
217 STATIONNAMING_ROAD,
218 STATIONNAMING_AIRPORT,
219 STATIONNAMING_OILRIG,
220 STATIONNAMING_DOCK,
221 STATIONNAMING_HELIPORT,
224 /** Information to handle station action 0 property 24 correctly */
225 struct StationNameInformation {
226 uint32_t free_names; ///< Current bitset of free names (we can remove names).
227 std::bitset<NUM_INDUSTRYTYPES> indtypes; ///< Bit set indicating when an industry type has been found.
231 * Find a station action 0 property 24 station name, or reduce the
232 * free_names if needed.
233 * @param tile the tile to search
234 * @param user_data the StationNameInformation to base the search on
235 * @return true if the tile contains an industry that has not given
236 * its name to one of the other stations in town.
238 static bool FindNearIndustryName(TileIndex tile, void *user_data)
240 /* All already found industry types */
241 StationNameInformation *sni = (StationNameInformation*)user_data;
242 if (!IsTileType(tile, MP_INDUSTRY)) return false;
244 /* If the station name is undefined it means that it doesn't name a station */
245 IndustryType indtype = GetIndustryType(tile);
246 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
248 /* In all cases if an industry that provides a name is found two of
249 * the standard names will be disabled. */
250 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
251 return !sni->indtypes[indtype];
254 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
256 static const uint32_t _gen_station_name_bits[] = {
257 0, // STATIONNAMING_RAIL
258 0, // STATIONNAMING_ROAD
259 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
260 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
261 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
262 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
265 const Town *t = st->town;
267 StationNameInformation sni{};
268 sni.free_names = UINT32_MAX;
270 for (const Station *s : Station::Iterate()) {
271 if (s != st && s->town == t) {
272 if (s->indtype != IT_INVALID) {
273 sni.indtypes[s->indtype] = true;
274 StringID name = GetIndustrySpec(s->indtype)->station_name;
275 if (name != STR_UNDEFINED) {
276 /* Filter for other industrytypes with the same name */
277 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
278 const IndustrySpec *indsp = GetIndustrySpec(it);
279 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
282 continue;
284 uint str = M(s->string_id);
285 if (str <= 0x20) {
286 if (str == M(STR_SV_STNAME_FOREST)) {
287 str = M(STR_SV_STNAME_WOODS);
289 ClrBit(sni.free_names, str);
294 TileIndex indtile = tile;
295 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
296 /* An industry has been found nearby */
297 IndustryType indtype = GetIndustryType(indtile);
298 const IndustrySpec *indsp = GetIndustrySpec(indtype);
299 /* STR_NULL means it only disables oil rig/mines */
300 if (indsp->station_name != STR_NULL) {
301 st->indtype = indtype;
302 return STR_SV_STNAME_FALLBACK;
306 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
308 /* check default names */
309 uint32_t tmp = sni.free_names & _gen_station_name_bits[name_class];
310 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
312 /* check mine? */
313 if (HasBit(sni.free_names, M(STR_SV_STNAME_MINES))) {
314 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
315 return STR_SV_STNAME_MINES;
319 /* check close enough to town to get central as name? */
320 if (DistanceMax(tile, t->xy) < 8) {
321 if (HasBit(sni.free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
323 if (HasBit(sni.free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
326 /* Check lakeside */
327 if (HasBit(sni.free_names, M(STR_SV_STNAME_LAKESIDE)) &&
328 DistanceFromEdge(tile) < 20 &&
329 CountMapSquareAround(tile, CMSAWater) >= 5) {
330 return STR_SV_STNAME_LAKESIDE;
333 /* Check woods */
334 if (HasBit(sni.free_names, M(STR_SV_STNAME_WOODS)) && (
335 CountMapSquareAround(tile, CMSATree) >= 8 ||
336 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
338 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
341 /* check elevation compared to town */
342 int z = GetTileZ(tile);
343 int z2 = GetTileZ(t->xy);
344 if (z < z2) {
345 if (HasBit(sni.free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
346 } else if (z > z2) {
347 if (HasBit(sni.free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
350 /* check direction compared to town */
351 static const int8_t _direction_and_table[] = {
352 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
353 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
354 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
355 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
358 sni.free_names &= _direction_and_table[
359 (TileX(tile) < TileX(t->xy)) +
360 (TileY(tile) < TileY(t->xy)) * 2];
362 /** Bitmask of remaining station names that can be used when a more specific name has not been used. */
363 static const uint32_t fallback_names = (
364 (1U << M(STR_SV_STNAME_NORTH)) |
365 (1U << M(STR_SV_STNAME_SOUTH)) |
366 (1U << M(STR_SV_STNAME_EAST)) |
367 (1U << M(STR_SV_STNAME_WEST)) |
368 (1U << M(STR_SV_STNAME_TRANSFER)) |
369 (1U << M(STR_SV_STNAME_HALT)) |
370 (1U << M(STR_SV_STNAME_EXCHANGE)) |
371 (1U << M(STR_SV_STNAME_ANNEXE)) |
372 (1U << M(STR_SV_STNAME_SIDINGS)) |
373 (1U << M(STR_SV_STNAME_BRANCH)) |
374 (1U << M(STR_SV_STNAME_UPPER)) |
375 (1U << M(STR_SV_STNAME_LOWER))
378 sni.free_names &= fallback_names;
379 return (sni.free_names == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(sni.free_names));
381 #undef M
384 * Find the closest deleted station of the current company
385 * @param tile the tile to search from.
386 * @return the closest station or nullptr if too far.
388 static Station *GetClosestDeletedStation(TileIndex tile)
390 uint threshold = 8;
392 Station *best_station = nullptr;
393 ForAllStationsRadius(tile, threshold, [&](Station *st) {
394 if (!st->IsInUse() && st->owner == _current_company) {
395 uint cur_dist = DistanceManhattan(tile, st->xy);
397 if (cur_dist < threshold) {
398 threshold = cur_dist;
399 best_station = st;
400 } else if (cur_dist == threshold && best_station != nullptr) {
401 /* In case of a tie, lowest station ID wins */
402 if (st->index < best_station->index) best_station = st;
407 return best_station;
411 void Station::GetTileArea(TileArea *ta, StationType type) const
413 switch (type) {
414 case STATION_RAIL:
415 *ta = this->train_station;
416 return;
418 case STATION_AIRPORT:
419 *ta = this->airport;
420 return;
422 case STATION_TRUCK:
423 *ta = this->truck_station;
424 return;
426 case STATION_BUS:
427 *ta = this->bus_station;
428 return;
430 case STATION_DOCK:
431 case STATION_OILRIG:
432 *ta = this->docking_station;
433 return;
435 default: NOT_REACHED();
440 * Update the virtual coords needed to draw the station sign.
442 void Station::UpdateVirtCoord()
444 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
446 pt.y -= 32 * ZOOM_BASE;
447 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
449 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
451 SetDParam(0, this->index);
452 SetDParam(1, this->facilities);
453 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION, STR_VIEWPORT_STATION_TINY);
455 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
457 SetWindowDirty(WC_STATION_VIEW, this->index);
461 * Move the station main coordinate somewhere else.
462 * @param new_xy new tile location of the sign
464 void Station::MoveSign(TileIndex new_xy)
466 if (this->xy == new_xy) return;
468 _station_kdtree.Remove(this->index);
470 this->BaseStation::MoveSign(new_xy);
472 _station_kdtree.Insert(this->index);
475 /** Update the virtual coords needed to draw the station sign for all stations. */
476 void UpdateAllStationVirtCoords()
478 for (BaseStation *st : BaseStation::Iterate()) {
479 st->UpdateVirtCoord();
483 void BaseStation::FillCachedName() const
485 auto tmp_params = MakeParameters(this->index);
486 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
489 void ClearAllStationCachedNames()
491 for (BaseStation *st : BaseStation::Iterate()) {
492 st->cached_name.clear();
497 * Get a mask of the cargo types that the station accepts.
498 * @param st Station to query
499 * @return the expected mask
501 CargoTypes GetAcceptanceMask(const Station *st)
503 CargoTypes mask = 0;
505 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
506 if (HasBit(it->status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, std::distance(std::begin(st->goods), it));
508 return mask;
512 * Get a mask of the cargo types that are empty at the station.
513 * @param st Station to query
514 * @return the empty mask
516 CargoTypes GetEmptyMask(const Station *st)
518 CargoTypes mask = 0;
520 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
521 if (it->cargo.TotalCount() == 0) SetBit(mask, std::distance(std::begin(st->goods), it));
523 return mask;
527 * Add news item for when a station changes which cargoes it accepts.
528 * @param st Station of cargo change.
529 * @param cargoes Bit mask of cargo types to list.
530 * @param reject True iff the station rejects the cargo types.
532 static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
534 SetDParam(0, st->index);
535 SetDParam(1, cargoes);
536 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
537 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
541 * Get the cargo types being produced around the tile (in a rectangle).
542 * @param north_tile Northern most tile of area
543 * @param w X extent of the area
544 * @param h Y extent of the area
545 * @param rad Search radius in addition to the given area
547 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
549 CargoArray produced{};
550 std::set<IndustryID> industries;
551 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
553 /* Loop over all tiles to get the produced cargo of
554 * everything except industries */
555 for (TileIndex tile : ta) {
556 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
557 AddProducedCargo(tile, produced);
560 /* Loop over the seen industries. They produce cargo for
561 * anything that is within 'rad' of any one of their tiles.
563 for (IndustryID industry : industries) {
564 const Industry *i = Industry::Get(industry);
565 /* Skip industry with neutral station */
566 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
568 for (const auto &p : i->produced) {
569 if (IsValidCargoID(p.cargo)) produced[p.cargo]++;
573 return produced;
577 * Get the acceptance of cargoes around the tile in 1/8.
578 * @param center_tile Center of the search area
579 * @param w X extent of area
580 * @param h Y extent of area
581 * @param rad Search radius in addition to given area
582 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
583 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
585 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
587 CargoArray acceptance{};
588 if (always_accepted != nullptr) *always_accepted = 0;
590 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
592 for (TileIndex tile : ta) {
593 /* Ignore industry if it has a neutral station. */
594 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
596 AddAcceptedCargo(tile, acceptance, always_accepted);
599 return acceptance;
603 * Get the acceptance of cargoes around the station in.
604 * @param st Station to get acceptance of.
605 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
607 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
609 CargoArray acceptance{};
610 if (always_accepted != nullptr) *always_accepted = 0;
612 BitmapTileIterator it(st->catchment_tiles);
613 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
614 AddAcceptedCargo(tile, acceptance, always_accepted);
617 return acceptance;
621 * Update the acceptance for a station.
622 * @param st Station to update
623 * @param show_msg controls whether to display a message that acceptance was changed.
625 void UpdateStationAcceptance(Station *st, bool show_msg)
627 /* old accepted goods types */
628 CargoTypes old_acc = GetAcceptanceMask(st);
630 /* And retrieve the acceptance. */
631 CargoArray acceptance{};
632 if (!st->rect.IsEmpty()) {
633 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
636 /* Adjust in case our station only accepts fewer kinds of goods */
637 for (CargoID i = 0; i < NUM_CARGO; i++) {
638 uint amt = acceptance[i];
640 /* Make sure the station can accept the goods type. */
641 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
642 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
643 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
644 amt = 0;
647 GoodsEntry &ge = st->goods[i];
648 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
649 if (LinkGraph::IsValidID(ge.link_graph)) {
650 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
654 /* Only show a message in case the acceptance was actually changed. */
655 CargoTypes new_acc = GetAcceptanceMask(st);
656 if (old_acc == new_acc) return;
658 /* show a message to report that the acceptance was changed? */
659 if (show_msg && st->owner == _local_company && st->IsInUse()) {
660 /* Combine old and new masks to get changes */
661 CargoTypes accepts = new_acc & ~old_acc;
662 CargoTypes rejects = ~new_acc & old_acc;
664 /* Show news message if there are any changes */
665 if (accepts != 0) ShowRejectOrAcceptNews(st, accepts, false);
666 if (rejects != 0) ShowRejectOrAcceptNews(st, rejects, true);
669 /* redraw the station view since acceptance changed */
670 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
673 static void UpdateStationSignCoord(BaseStation *st)
675 const StationRect *r = &st->rect;
677 if (r->IsEmpty()) return; // no tiles belong to this station
679 /* clamp sign coord to be inside the station rect */
680 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
681 st->MoveSign(new_xy);
683 if (!Station::IsExpected(st)) return;
684 Station *full_station = Station::From(st);
685 for (const GoodsEntry &ge : full_station->goods) {
686 LinkGraphID lg = ge.link_graph;
687 if (!LinkGraph::IsValidID(lg)) continue;
688 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
693 * Common part of building various station parts and possibly attaching them to an existing one.
694 * @param[in,out] st Station to attach to
695 * @param flags Command flags
696 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
697 * @param area Area occupied by the new part
698 * @param name_class Station naming class to use to generate the new station's name
699 * @return Command error that occurred, if any
701 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
703 /* Find a deleted station close to us */
704 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
706 if (*st != nullptr) {
707 if ((*st)->owner != _current_company) {
708 return_cmd_error(CMD_ERROR);
711 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
712 if (ret.Failed()) return ret;
713 } else {
714 /* allocate and initialize new station */
715 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
717 if (flags & DC_EXEC) {
718 *st = new Station(area.tile);
719 _station_kdtree.Insert((*st)->index);
721 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
722 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
724 if (Company::IsValidID(_current_company)) {
725 SetBit((*st)->town->have_ratings, _current_company);
729 return CommandCost();
733 * This is called right after a station was deleted.
734 * It checks if the whole station is free of substations, and if so, the station will be
735 * deleted after a little while.
736 * @param st Station
738 static void DeleteStationIfEmpty(BaseStation *st)
740 if (!st->IsInUse()) {
741 st->delete_ctr = 0;
742 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
744 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
745 UpdateStationSignCoord(st);
749 * After adding/removing tiles to station, update some station-related stuff.
750 * @param adding True if adding tiles, false if removing them.
751 * @param type StationType being modified.
753 void Station::AfterStationTileSetChange(bool adding, StationType type)
755 this->UpdateVirtCoord();
756 DirtyCompanyInfrastructureWindows(this->owner);
758 if (adding) {
759 this->RecomputeCatchment();
760 MarkCatchmentTilesDirty();
761 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
762 } else {
763 MarkCatchmentTilesDirty();
766 switch (type) {
767 case STATION_RAIL:
768 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
769 break;
770 case STATION_AIRPORT:
771 break;
772 case STATION_TRUCK:
773 case STATION_BUS:
774 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
775 break;
776 case STATION_DOCK:
777 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
778 break;
779 default: NOT_REACHED();
782 if (adding) {
783 UpdateStationAcceptance(this, false);
784 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
785 } else {
786 DeleteStationIfEmpty(this);
787 this->RecomputeCatchment();
792 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
795 * Checks if the given tile is buildable, flat and has a certain height.
796 * @param tile TileIndex to check.
797 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
798 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
799 * @param allow_steep Whether steep slopes are allowed.
800 * @param check_bridge Check for the existence of a bridge.
801 * @return The cost in case of success, or an error code if it failed.
803 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
805 if (check_bridge && IsBridgeAbove(tile)) {
806 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
809 CommandCost ret = EnsureNoVehicleOnGround(tile);
810 if (ret.Failed()) return ret;
812 auto [tileh, z] = GetTileSlopeZ(tile);
814 /* Prohibit building if
815 * 1) The tile is "steep" (i.e. stretches two height levels).
816 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
818 if ((!allow_steep && IsSteepSlope(tileh)) ||
819 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
820 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
823 CommandCost cost(EXPENSES_CONSTRUCTION);
824 int flat_z = z + GetSlopeMaxZ(tileh);
825 if (tileh != SLOPE_FLAT) {
826 /* Forbid building if the tile faces a slope in a invalid direction. */
827 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
828 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
829 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
832 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
835 /* The level of this tile must be equal to allowed_z. */
836 if (allowed_z < 0) {
837 /* First tile. */
838 allowed_z = flat_z;
839 } else if (allowed_z != flat_z) {
840 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
843 return cost;
847 * Checks if an airport can be built at the given location and clear the area.
848 * @param tile_iter Airport tile iterator.
849 * @param flags Operation to perform.
850 * @return The cost in case of success, or an error code if it failed.
852 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
854 CommandCost cost(EXPENSES_CONSTRUCTION);
855 int allowed_z = -1;
857 for (; tile_iter != INVALID_TILE; ++tile_iter) {
858 CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
859 if (ret.Failed()) return ret;
860 cost.AddCost(ret);
862 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
863 if (ret.Failed()) return ret;
864 cost.AddCost(ret);
867 return cost;
871 * Checks if a rail station can be built at the given tile.
872 * @param tile_cur Tile to check.
873 * @param north_tile North tile of the area being checked.
874 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
875 * @param flags Operation to perform.
876 * @param axis Rail station axis.
877 * @param station StationID to be queried and returned if available.
878 * @param rt The rail type to check for (overbuilding rail stations over rail).
879 * @param affected_vehicles List of trains with PBS reservations on the tiles
880 * @param spec_class Station class.
881 * @param spec_index Index into the station class.
882 * @param plat_len Platform length.
883 * @param numtracks Number of platforms.
884 * @return The cost in case of success, or an error code if it failed.
886 static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
888 CommandCost cost(EXPENSES_CONSTRUCTION);
889 uint invalid_dirs = 5 << axis;
891 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
892 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
894 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
895 if (ret.Failed()) return ret;
896 cost.AddCost(ret);
898 if (slope_cb) {
899 /* Do slope check if requested. */
900 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
901 if (ret.Failed()) return ret;
904 /* if station is set, then we have special handling to allow building on top of already existing stations.
905 * so station points to INVALID_STATION if we can build on any station.
906 * Or it points to a station if we're only allowed to build on exactly that station. */
907 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
908 if (!IsRailStation(tile_cur)) {
909 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
910 } else {
911 StationID st = GetStationIndex(tile_cur);
912 if (*station == INVALID_STATION) {
913 *station = st;
914 } else if (*station != st) {
915 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
918 } else {
919 /* Rail type is only valid when building a railway station; if station to
920 * build isn't a rail station it's INVALID_RAILTYPE. */
921 if (rt != INVALID_RAILTYPE &&
922 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
923 HasPowerOnRail(GetRailType(tile_cur), rt)) {
924 /* Allow overbuilding if the tile:
925 * - has rail, but no signals
926 * - it has exactly one track
927 * - the track is in line with the station
928 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
930 TrackBits tracks = GetTrackBits(tile_cur);
931 Track track = RemoveFirstTrack(&tracks);
932 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
934 if (tracks == TRACK_BIT_NONE && track == expected_track) {
935 /* Check for trains having a reservation for this tile. */
936 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
937 Train *v = GetTrainForReservation(tile_cur, track);
938 if (v != nullptr) {
939 affected_vehicles.push_back(v);
942 ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
943 if (ret.Failed()) return ret;
944 cost.AddCost(ret);
945 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
946 return cost;
949 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
950 if (ret.Failed()) return ret;
951 cost.AddCost(ret);
954 return cost;
958 * Checks if a road stop can be built at the given tile.
959 * @param cur_tile Tile to check.
960 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
961 * @param flags Operation to perform.
962 * @param invalid_dirs Prohibited directions (set of DiagDirections).
963 * @param is_drive_through True if trying to build a drive-through station.
964 * @param station_type Station type (bus, truck or road waypoint).
965 * @param axis Axis of a drive-through road stop.
966 * @param station StationID to be queried and returned if available.
967 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
968 * @return The cost in case of success, or an error code if it failed.
970 CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
972 CommandCost cost(EXPENSES_CONSTRUCTION);
974 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
975 if (ret.Failed()) return ret;
976 cost.AddCost(ret);
978 /* If station is set, then we have special handling to allow building on top of already existing stations.
979 * Station points to INVALID_STATION if we can build on any station.
980 * Or it points to a station if we're only allowed to build on exactly that station. */
981 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
982 if (!IsAnyRoadStop(cur_tile)) {
983 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
984 } else {
985 if (station_type != GetStationType(cur_tile) ||
986 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
987 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
989 /* Drive-through station in the wrong direction. */
990 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis) {
991 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
993 StationID st = GetStationIndex(cur_tile);
994 if (*station == INVALID_STATION) {
995 *station = st;
996 } else if (*station != st) {
997 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1000 } else {
1001 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1002 /* Road bits in the wrong direction. */
1003 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
1004 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
1005 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1006 switch (CountBits(rb)) {
1007 case 1:
1008 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1010 case 2:
1011 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1012 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1014 default: // 3 or 4
1015 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1019 if (build_over_road) {
1020 /* There is a road, check if we can build road+tram stop over it. */
1021 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1022 if (road_rt != INVALID_ROADTYPE) {
1023 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1024 if (road_owner == OWNER_TOWN) {
1025 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1026 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1027 ret = CheckOwnership(road_owner);
1028 if (ret.Failed()) return ret;
1030 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1032 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1034 if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1035 ret = CheckOwnership(road_owner);
1036 if (ret.Failed()) return ret;
1039 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1040 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1041 cost.AddCost(RoadBuildCost(rt) * 2);
1044 /* There is a tram, check if we can build road+tram stop over it. */
1045 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1046 if (tram_rt != INVALID_ROADTYPE) {
1047 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1048 if (Company::IsValidID(tram_owner) &&
1049 (!_settings_game.construction.road_stop_on_competitor_road ||
1050 /* Disallow breaking end-of-line of someone else
1051 * so trams can still reverse on this tile. */
1052 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1053 ret = CheckOwnership(tram_owner);
1054 if (ret.Failed()) return ret;
1056 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1058 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1060 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1061 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1062 cost.AddCost(RoadBuildCost(rt) * 2);
1064 } else if (rt == INVALID_ROADTYPE) {
1065 return_cmd_error(STR_ERROR_THERE_IS_NO_ROAD);
1066 } else {
1067 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1068 if (ret.Failed()) return ret;
1069 cost.AddCost(ret);
1070 cost.AddCost(RoadBuildCost(rt) * 2);
1074 return cost;
1078 * Check whether we can expand the rail part of the given station.
1079 * @param st the station to expand
1080 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1081 * @return Succeeded or failed command.
1083 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
1085 TileArea cur_ta = st->train_station;
1087 /* determine new size of train station region.. */
1088 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1089 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1090 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1091 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1092 new_ta.tile = TileXY(x, y);
1094 /* make sure the final size is not too big. */
1095 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1096 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1099 return CommandCost();
1102 static inline uint8_t *CreateSingle(uint8_t *layout, int n)
1104 int i = n;
1105 do *layout++ = 0; while (--i);
1106 layout[((n - 1) >> 1) - n] = 2;
1107 return layout;
1110 static inline uint8_t *CreateMulti(uint8_t *layout, int n, uint8_t b)
1112 int i = n;
1113 do *layout++ = b; while (--i);
1114 if (n > 4) {
1115 layout[0 - n] = 0;
1116 layout[n - 1 - n] = 0;
1118 return layout;
1122 * Create the station layout for the given number of tracks and platform length.
1123 * @param layout The layout to write to.
1124 * @param numtracks The number of tracks to write.
1125 * @param plat_len The length of the platforms.
1126 * @param statspec The specification of the station to (possibly) get the layout from.
1128 void GetStationLayout(uint8_t *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1130 if (statspec != nullptr) {
1131 auto found = statspec->layouts.find(GetStationLayoutKey(numtracks, plat_len));
1132 if (found != std::end(statspec->layouts)) {
1133 /* Custom layout defined, copy to buffer. */
1134 std::copy(std::begin(found->second), std::end(found->second), layout);
1135 return;
1139 if (plat_len == 1) {
1140 CreateSingle(layout, numtracks);
1141 } else {
1142 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1143 int n = numtracks >> 1;
1145 while (--n >= 0) {
1146 layout = CreateMulti(layout, plat_len, 4);
1147 layout = CreateMulti(layout, plat_len, 6);
1153 * Find a nearby station that joins this station.
1154 * @tparam T the class to find a station for
1155 * @tparam error_message the error message when building a station on top of others
1156 * @tparam F the filter functor type
1157 * @param existing_station an existing station we build over
1158 * @param station_to_join the station to join to
1159 * @param adjacent whether adjacent stations are allowed
1160 * @param ta the area of the newly build station
1161 * @param st 'return' pointer for the found station
1162 * @return command cost with the error or 'okay'
1164 template <class T, StringID error_message, class F>
1165 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1167 assert(*st == nullptr);
1168 bool check_surrounding = true;
1170 if (_settings_game.station.adjacent_stations) {
1171 if (existing_station != INVALID_STATION) {
1172 if (adjacent && existing_station != station_to_join) {
1173 /* You can't build an adjacent station over the top of one that
1174 * already exists. */
1175 return_cmd_error(error_message);
1176 } else {
1177 /* Extend the current station, and don't check whether it will
1178 * be near any other stations. */
1179 T *candidate = T::GetIfValid(existing_station);
1180 if (candidate != nullptr && filter(candidate)) *st = candidate;
1181 check_surrounding = (*st == nullptr);
1183 } else {
1184 /* There's no station here. Don't check the tiles surrounding this
1185 * one if the company wanted to build an adjacent station. */
1186 if (adjacent) check_surrounding = false;
1190 if (check_surrounding) {
1191 /* Make sure there is no more than one other station around us that is owned by us. */
1192 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1193 if (ret.Failed()) return ret;
1196 /* Distant join */
1197 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1199 return CommandCost();
1203 * Find a nearby station that joins this station.
1204 * @param existing_station an existing station we build over
1205 * @param station_to_join the station to join to
1206 * @param adjacent whether adjacent stations are allowed
1207 * @param ta the area of the newly build station
1208 * @param st 'return' pointer for the found station
1209 * @return command cost with the error or 'okay'
1211 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1213 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1217 * Find a nearby waypoint that joins this waypoint.
1218 * @param existing_waypoint an existing waypoint we build over
1219 * @param waypoint_to_join the waypoint to join to
1220 * @param adjacent whether adjacent waypoints are allowed
1221 * @param ta the area of the newly build waypoint
1222 * @param wp 'return' pointer for the found waypoint
1223 * @param is_road whether to find a road waypoint
1224 * @return command cost with the error or 'okay'
1226 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1228 if (is_road) {
1229 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD); });
1230 } else {
1231 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return !HasBit(wp->waypoint_flags, WPF_ROAD); });
1236 * Clear platform reservation during station building/removing.
1237 * @param v vehicle which holds reservation
1239 static void FreeTrainReservation(Train *v)
1241 FreeTrainTrackReservation(v);
1242 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1243 v = v->Last();
1244 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1248 * Restore platform reservation during station building/removing.
1249 * @param v vehicle which held reservation
1251 static void RestoreTrainReservation(Train *v)
1253 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1254 TryPathReserve(v, true, true);
1255 v = v->Last();
1256 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1260 * Calculates cost of new rail stations within the area.
1261 * @param tile_area Area to check.
1262 * @param flags Operation to perform.
1263 * @param axis Rail station axis.
1264 * @param station StationID to be queried and returned if available.
1265 * @param rt The rail type to check for (overbuilding rail stations over rail).
1266 * @param affected_vehicles List of trains with PBS reservations on the tiles
1267 * @param spec_class Station class.
1268 * @param spec_index Index into the station class.
1269 * @param plat_len Platform length.
1270 * @param numtracks Number of platforms.
1271 * @return The cost in case of success, or an error code if it failed.
1273 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, uint8_t plat_len, uint8_t numtracks)
1275 CommandCost cost(EXPENSES_CONSTRUCTION);
1276 bool length_price_ready = true;
1277 uint8_t tracknum = 0;
1278 int allowed_z = -1;
1279 for (TileIndex cur_tile : tile_area) {
1280 /* Clear the land below the station. */
1281 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1282 if (ret.Failed()) return ret;
1284 /* Only add _price[PR_BUILD_STATION_RAIL_LENGTH] once for each valid plat_len. */
1285 if (tracknum == numtracks) {
1286 length_price_ready = true;
1287 tracknum = 0;
1288 } else {
1289 tracknum++;
1292 /* AddCost for new or rotated rail stations. */
1293 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1294 cost.AddCost(ret);
1295 cost.AddCost(_price[PR_BUILD_STATION_RAIL]);
1296 cost.AddCost(RailBuildCost(rt));
1298 if (length_price_ready) {
1299 cost.AddCost(_price[PR_BUILD_STATION_RAIL_LENGTH]);
1300 length_price_ready = false;
1305 return cost;
1309 * Get station tile flags for the given StationGfx.
1310 * @param gfx StationGfx of station tile.
1311 * @param statspec Station spec of station tile.
1312 * @return Tile flags to apply.
1314 static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
1316 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1317 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlags::Pylons : StationSpec::TileFlags::None;
1318 return statspec->tileflags[gfx];
1322 * Set rail station tile flags for the given tile.
1323 * @param tile Tile to set flags on.
1324 * @param statspec Statspec of the tile.
1326 void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
1328 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1329 SetStationTileBlocked(tile, HasFlag(flags, StationSpec::TileFlags::Blocked));
1330 SetStationTileHavePylons(tile, HasFlag(flags, StationSpec::TileFlags::Pylons));
1331 SetStationTileHaveWires(tile, !HasFlag(flags, StationSpec::TileFlags::NoWires));
1335 * Build rail station
1336 * @param flags operation to perform
1337 * @param tile_org northern most position of station dragging/placement
1338 * @param rt railtype
1339 * @param axis orientation (Axis)
1340 * @param numtracks number of tracks
1341 * @param plat_len platform length
1342 * @param spec_class custom station class
1343 * @param spec_index custom station id
1344 * @param station_to_join station ID to join (NEW_STATION if build new one)
1345 * @param adjacent allow stations directly adjacent to other stations.
1346 * @return the cost of this operation or an error
1348 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1350 /* Does the authority allow this? */
1351 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1352 if (ret.Failed()) return ret;
1354 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1356 /* Check if the given station class is valid */
1357 if (static_cast<uint>(spec_class) >= StationClass::GetClassCount()) return CMD_ERROR;
1358 const StationClass *cls = StationClass::Get(spec_class);
1359 if (IsWaypointClass(*cls)) return CMD_ERROR;
1360 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1361 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1363 int w_org, h_org;
1364 if (axis == AXIS_X) {
1365 w_org = plat_len;
1366 h_org = numtracks;
1367 } else {
1368 h_org = plat_len;
1369 w_org = numtracks;
1372 bool reuse = (station_to_join != NEW_STATION);
1373 if (!reuse) station_to_join = INVALID_STATION;
1374 bool distant_join = (station_to_join != INVALID_STATION);
1376 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1378 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1380 /* these values are those that will be stored in train_tile and station_platforms */
1381 TileArea new_location(tile_org, w_org, h_org);
1383 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1384 StationID est = INVALID_STATION;
1385 std::vector<Train *> affected_vehicles;
1386 /* Add construction and clearing expenses. */
1387 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1388 if (cost.Failed()) return cost;
1390 Station *st = nullptr;
1391 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1392 if (ret.Failed()) return ret;
1394 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1395 if (ret.Failed()) return ret;
1397 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1398 ret = CanExpandRailStation(st, new_location);
1399 if (ret.Failed()) return ret;
1402 /* Check if we can allocate a custom stationspec to this station */
1403 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1404 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1405 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1407 if (statspec != nullptr) {
1408 /* Perform NewStation checks */
1410 /* Check if the station size is permitted */
1411 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1412 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return_cmd_error(STR_ERROR_STATION_DISALLOWED_LENGTH);
1414 /* Check if the station is buildable */
1415 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1416 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1417 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1421 if (flags & DC_EXEC) {
1422 TileIndexDiff tile_delta;
1423 uint8_t numtracks_orig;
1424 Track track;
1426 st->train_station = new_location;
1427 st->AddFacility(FACIL_TRAIN, new_location.tile);
1429 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1431 if (statspec != nullptr) {
1432 /* Include this station spec's animation trigger bitmask
1433 * in the station's cached copy. */
1434 st->cached_anim_triggers |= statspec->animation.triggers;
1437 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1438 track = AxisToTrack(axis);
1440 std::vector<uint8_t> layouts(numtracks * plat_len);
1441 GetStationLayout(layouts.data(), numtracks, plat_len, statspec);
1443 numtracks_orig = numtracks;
1445 Company *c = Company::Get(st->owner);
1446 size_t layout_idx = 0;
1447 TileIndex tile_track = tile_org;
1448 do {
1449 TileIndex tile = tile_track;
1450 int w = plat_len;
1451 do {
1452 uint8_t layout = layouts[layout_idx++];
1453 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1454 /* Check for trains having a reservation for this tile. */
1455 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1456 if (v != nullptr) {
1457 affected_vehicles.push_back(v);
1458 FreeTrainReservation(v);
1462 /* Railtype can change when overbuilding. */
1463 if (IsRailStationTile(tile)) {
1464 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1465 c->infrastructure.station--;
1468 /* Remove animation if overbuilding */
1469 DeleteAnimatedTile(tile);
1470 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1471 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1472 /* Free the spec if we overbuild something */
1473 DeallocateSpecFromStation(st, old_specindex);
1475 SetCustomStationSpecIndex(tile, specindex);
1476 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1477 SetAnimationFrame(tile, 0);
1479 if (statspec != nullptr) {
1480 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1481 uint32_t platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1483 /* As the station is not yet completely finished, the station does not yet exist. */
1484 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1485 if (callback != CALLBACK_FAILED) {
1486 if (callback <= UINT8_MAX) {
1487 SetStationGfx(tile, (callback & ~1) + axis);
1488 } else {
1489 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_BUILD_TILE_LAYOUT, callback);
1493 /* Trigger station animation -- after building? */
1494 TriggerStationAnimation(st, tile, SAT_BUILT);
1497 SetRailStationTileFlags(tile, statspec);
1499 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1500 c->infrastructure.station++;
1502 tile += tile_delta;
1503 } while (--w);
1504 AddTrackToSignalBuffer(tile_track, track, _current_company);
1505 YapfNotifyTrackLayoutChange(tile_track, track);
1506 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1507 } while (--numtracks);
1509 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1510 /* Restore reservations of trains. */
1511 RestoreTrainReservation(affected_vehicles[i]);
1514 /* Check whether we need to expand the reservation of trains already on the station. */
1515 TileArea update_reservation_area;
1516 if (axis == AXIS_X) {
1517 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1518 } else {
1519 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1522 for (TileIndex tile : update_reservation_area) {
1523 /* Don't even try to make eye candy parts reserved. */
1524 if (IsStationTileBlocked(tile)) continue;
1526 DiagDirection dir = AxisToDiagDir(axis);
1527 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1528 TileIndex platform_begin = tile;
1529 TileIndex platform_end = tile;
1531 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1532 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1533 platform_begin = next_tile;
1535 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1536 platform_end = next_tile;
1539 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1540 bool reservation = false;
1541 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1542 reservation = HasStationReservation(t);
1545 if (reservation) {
1546 SetRailStationPlatformReservation(platform_begin, dir, true);
1550 st->MarkTilesDirty(false);
1551 st->AfterStationTileSetChange(true, STATION_RAIL);
1554 return cost;
1557 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1559 restart:
1561 /* too small? */
1562 if (ta.w != 0 && ta.h != 0) {
1563 /* check the left side, x = constant, y changes */
1564 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1565 /* the left side is unused? */
1566 if (++i == ta.h) {
1567 ta.tile += TileDiffXY(1, 0);
1568 ta.w--;
1569 goto restart;
1573 /* check the right side, x = constant, y changes */
1574 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1575 /* the right side is unused? */
1576 if (++i == ta.h) {
1577 ta.w--;
1578 goto restart;
1582 /* check the upper side, y = constant, x changes */
1583 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1584 /* the left side is unused? */
1585 if (++i == ta.w) {
1586 ta.tile += TileDiffXY(0, 1);
1587 ta.h--;
1588 goto restart;
1592 /* check the lower side, y = constant, x changes */
1593 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1594 /* the left side is unused? */
1595 if (++i == ta.w) {
1596 ta.h--;
1597 goto restart;
1600 } else {
1601 ta.Clear();
1604 return ta;
1607 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1609 return st->TileBelongsToRailStation(tile);
1612 static void MakeRailStationAreaSmaller(BaseStation *st)
1614 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1617 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1619 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1622 static void MakeShipStationAreaSmaller(Station *st)
1624 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1625 UpdateStationDockingTiles(st);
1628 static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1630 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1633 void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1635 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1639 * Remove a number of tiles from any rail station within the area.
1640 * @param ta the area to clear station tile from.
1641 * @param affected_stations the stations affected.
1642 * @param flags the command flags.
1643 * @param removal_cost the cost for removing the tile, including the rail.
1644 * @param keep_rail whether to keep the rail of the station.
1645 * @tparam T the type of station to remove.
1646 * @return the number of cleared tiles or an error.
1648 template <class T>
1649 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1651 /* Count of the number of tiles removed */
1652 int quantity = 0;
1653 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1654 /* Accumulator for the errors seen during clearing. If no errors happen,
1655 * and the quantity is 0 there is no station. Otherwise it will be one
1656 * of the other error that got accumulated. */
1657 CommandCost error;
1659 /* Do the action for every tile into the area */
1660 for (TileIndex tile : ta) {
1661 /* Make sure the specified tile is a rail station */
1662 if (!HasStationTileRail(tile)) continue;
1664 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1665 CommandCost ret = EnsureNoVehicleOnGround(tile);
1666 error.AddCost(ret);
1667 if (ret.Failed()) continue;
1669 /* Check ownership of station */
1670 T *st = T::GetByTile(tile);
1671 if (st == nullptr) continue;
1673 if (_current_company != OWNER_WATER) {
1674 ret = CheckOwnership(st->owner);
1675 error.AddCost(ret);
1676 if (ret.Failed()) continue;
1679 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1680 quantity++;
1682 if (keep_rail || IsStationTileBlocked(tile)) {
1683 /* Don't refund the 'steel' of the track when we keep the
1684 * rail, or when the tile didn't have any rail at all. */
1685 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1688 if (flags & DC_EXEC) {
1689 /* read variables before the station tile is removed */
1690 uint specindex = GetCustomStationSpecIndex(tile);
1691 Track track = GetRailStationTrack(tile);
1692 Owner owner = GetTileOwner(tile);
1693 RailType rt = GetRailType(tile);
1694 Train *v = nullptr;
1696 if (HasStationReservation(tile)) {
1697 v = GetTrainForReservation(tile, track);
1698 if (v != nullptr) FreeTrainReservation(v);
1701 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1702 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1704 DoClearSquare(tile);
1705 DeleteNewGRFInspectWindow(GSF_STATIONS, tile.base());
1706 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1707 Company::Get(owner)->infrastructure.station--;
1708 DirtyCompanyInfrastructureWindows(owner);
1710 st->rect.AfterRemoveTile(st, tile);
1711 AddTrackToSignalBuffer(tile, track, owner);
1712 YapfNotifyTrackLayoutChange(tile, track);
1714 DeallocateSpecFromStation(st, specindex);
1716 include(affected_stations, st);
1718 if (v != nullptr) RestoreTrainReservation(v);
1722 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1724 for (T *st : affected_stations) {
1726 /* now we need to make the "spanned" area of the railway station smaller
1727 * if we deleted something at the edges.
1728 * we also need to adjust train_tile. */
1729 MakeRailStationAreaSmaller(st);
1730 UpdateStationSignCoord(st);
1732 /* if we deleted the whole station, delete the train facility. */
1733 if (st->train_station.tile == INVALID_TILE) {
1734 st->facilities &= ~FACIL_TRAIN;
1735 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
1736 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1737 MarkCatchmentTilesDirty();
1738 st->UpdateVirtCoord();
1739 DeleteStationIfEmpty(st);
1743 total_cost.AddCost(quantity * removal_cost);
1744 return total_cost;
1748 * Remove a single tile from a rail station.
1749 * This allows for custom-built station with holes and weird layouts
1750 * @param flags operation to perform
1751 * @param start tile of station piece to remove
1752 * @param end other edge of the rect to remove
1753 * @param keep_rail if set keep the rail
1754 * @return the cost of this operation or an error
1756 CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1758 if (end == 0) end = start;
1759 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1761 TileArea ta(start, end);
1762 std::vector<Station *> affected_stations;
1764 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1765 if (ret.Failed()) return ret;
1767 /* Do all station specific functions here. */
1768 for (Station *st : affected_stations) {
1770 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1771 st->MarkTilesDirty(false);
1772 MarkCatchmentTilesDirty();
1773 st->RecomputeCatchment();
1776 /* Now apply the rail cost to the number that we deleted */
1777 return ret;
1781 * Remove a single tile from a waypoint.
1782 * This allows for custom-built waypoint with holes and weird layouts
1783 * @param flags operation to perform
1784 * @param start tile of waypoint piece to remove
1785 * @param end other edge of the rect to remove
1786 * @param keep_rail if set keep the rail
1787 * @return the cost of this operation or an error
1789 CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1791 if (end == 0) end = start;
1792 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1794 TileArea ta(start, end);
1795 std::vector<Waypoint *> affected_stations;
1797 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1802 * Remove a rail station/waypoint
1803 * @param st The station/waypoint to remove the rail part from
1804 * @param flags operation to perform
1805 * @param removal_cost the cost for removing a tile
1806 * @tparam T the type of station to remove
1807 * @return cost or failure of operation
1809 template <class T>
1810 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1812 /* Current company owns the station? */
1813 if (_current_company != OWNER_WATER) {
1814 CommandCost ret = CheckOwnership(st->owner);
1815 if (ret.Failed()) return ret;
1818 /* determine width and height of platforms */
1819 TileArea ta = st->train_station;
1821 assert(ta.w != 0 && ta.h != 0);
1823 CommandCost cost(EXPENSES_CONSTRUCTION);
1824 /* clear all areas of the station */
1825 for (TileIndex tile : ta) {
1826 /* only remove tiles that are actually train station tiles */
1827 if (st->TileBelongsToRailStation(tile)) {
1828 std::vector<T*> affected_stations; // dummy
1829 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1830 if (ret.Failed()) return ret;
1831 cost.AddCost(ret);
1835 return cost;
1839 * Remove a rail station
1840 * @param tile Tile of the station.
1841 * @param flags operation to perform
1842 * @return cost or failure of operation
1844 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1846 /* if there is flooding, remove platforms tile by tile */
1847 if (_current_company == OWNER_WATER) {
1848 return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1851 Station *st = Station::GetByTile(tile);
1852 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1854 if (flags & DC_EXEC) st->RecomputeCatchment();
1856 return cost;
1860 * Remove a rail waypoint
1861 * @param tile Tile of the waypoint.
1862 * @param flags operation to perform
1863 * @return cost or failure of operation
1865 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1867 /* if there is flooding, remove waypoints tile by tile */
1868 if (_current_company == OWNER_WATER) {
1869 return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1872 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1877 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1878 * @param st The Station to do the whole procedure for
1879 * @return a pointer to where to link a new RoadStop*
1881 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1883 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1885 if (*primary_stop == nullptr) {
1886 /* we have no roadstop of the type yet, so write a "primary stop" */
1887 return primary_stop;
1888 } else {
1889 /* there are stops already, so append to the end of the list */
1890 RoadStop *stop = *primary_stop;
1891 while (stop->next != nullptr) stop = stop->next;
1892 return &stop->next;
1896 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1897 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index = -1);
1900 * Find a nearby station that joins this road stop.
1901 * @param existing_stop an existing road stop we build over
1902 * @param station_to_join the station to join to
1903 * @param adjacent whether adjacent stations are allowed
1904 * @param ta the area of the newly build station
1905 * @param st 'return' pointer for the found station
1906 * @return command cost with the error or 'okay'
1908 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1910 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1914 * Calculates cost of new road stops within the area.
1915 * @param tile_area Area to check.
1916 * @param flags Operation to perform.
1917 * @param is_drive_through True if trying to build a drive-through station.
1918 * @param station_type Station type (bus, truck or road waypoint).
1919 * @param axis Axis of a drive-through road stop.
1920 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1921 * @param station StationID to be queried and returned if available.
1922 * @param rt Road type to build, may be INVALID_ROADTYPE if an existing road is required.
1923 * @param unit_cost The cost to build one road stop of the current type.
1924 * @return The cost in case of success, or an error code if it failed.
1926 CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlag flags, bool is_drive_through, StationType station_type, Axis axis, DiagDirection ddir, StationID *est, RoadType rt, Money unit_cost)
1928 uint invalid_dirs = 0;
1929 if (is_drive_through) {
1930 SetBit(invalid_dirs, AxisToDiagDir(axis));
1931 SetBit(invalid_dirs, ReverseDiagDir(AxisToDiagDir(axis)));
1932 } else {
1933 SetBit(invalid_dirs, ddir);
1936 /* Check every tile in the area. */
1937 int allowed_z = -1;
1938 CommandCost cost(EXPENSES_CONSTRUCTION);
1939 for (TileIndex cur_tile : tile_area) {
1940 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, flags, invalid_dirs, is_drive_through, station_type, axis, est, rt);
1941 if (ret.Failed()) return ret;
1943 bool is_preexisting_roadstop = IsTileType(cur_tile, MP_STATION) && IsAnyRoadStop(cur_tile);
1945 /* Only add costs if a stop doesn't already exist in the location */
1946 if (!is_preexisting_roadstop) {
1947 cost.AddCost(ret);
1948 cost.AddCost(unit_cost);
1952 return cost;
1956 * Build a bus or truck stop.
1957 * @param flags Operation to perform.
1958 * @param tile Northernmost tile of the stop.
1959 * @param width Width of the road stop.
1960 * @param length Length of the road stop.
1961 * @param stop_type Type of road stop (bus/truck).
1962 * @param is_drive_through False for normal stops, true for drive-through.
1963 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1964 * @param rt The roadtype.
1965 * @param spec_class Road stop spec class.
1966 * @param spec_index Road stop spec index.
1967 * @param station_to_join Station ID to join (NEW_STATION if build new one).
1968 * @param adjacent Allow stations directly adjacent to other stations.
1969 * @return The cost of this operation or an error.
1971 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
1972 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1974 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1975 bool reuse = (station_to_join != NEW_STATION);
1976 if (!reuse) station_to_join = INVALID_STATION;
1977 bool distant_join = (station_to_join != INVALID_STATION);
1979 /* Check if the given station class is valid */
1980 if (static_cast<uint>(spec_class) >= RoadStopClass::GetClassCount()) return CMD_ERROR;
1981 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
1982 if (IsWaypointClass(*cls)) return CMD_ERROR;
1983 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1985 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
1986 if (roadstopspec != nullptr) {
1987 if (stop_type == ROADSTOP_TRUCK && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1988 if (stop_type == ROADSTOP_BUS && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
1989 if (!is_drive_through && HasBit(roadstopspec->flags, RSF_DRIVE_THROUGH_ONLY)) return CMD_ERROR;
1992 /* Check if the requested road stop is too big */
1993 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1994 /* Check for incorrect width / length. */
1995 if (width == 0 || length == 0) return CMD_ERROR;
1996 /* Check if the first tile and the last tile are valid */
1997 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1999 TileArea roadstop_area(tile, width, length);
2001 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2003 /* Trams only have drive through stops */
2004 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2006 Axis axis = DiagDirToAxis(ddir);
2008 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2009 if (ret.Failed()) return ret;
2011 bool is_truck_stop = stop_type != ROADSTOP_BUS;
2013 /* Total road stop cost. */
2014 Money unit_cost;
2015 if (roadstopspec != nullptr) {
2016 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS);
2017 } else {
2018 unit_cost = _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS];
2020 StationID est = INVALID_STATION;
2021 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? STATION_TRUCK : STATION_BUS, axis, ddir, &est, rt, unit_cost);
2022 if (cost.Failed()) return cost;
2024 Station *st = nullptr;
2025 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2026 if (ret.Failed()) return ret;
2028 /* Check if this number of road stops can be allocated. */
2029 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);
2031 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
2032 if (ret.Failed()) return ret;
2034 /* Check if we can allocate a custom stationspec to this station */
2035 int specindex = AllocateSpecToRoadStop(roadstopspec, st, (flags & DC_EXEC) != 0);
2036 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
2038 if (roadstopspec != nullptr) {
2039 /* Perform NewGRF checks */
2041 /* Check if the road stop is buildable */
2042 if (HasBit(roadstopspec->callback_mask, CBM_ROAD_STOP_AVAIL)) {
2043 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? STATION_TRUCK : STATION_BUS, 0);
2044 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2048 if (flags & DC_EXEC) {
2049 /* Check every tile in the area. */
2050 for (TileIndex cur_tile : roadstop_area) {
2051 /* Get existing road types and owners before any tile clearing */
2052 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
2053 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
2054 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
2055 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
2057 if (IsTileType(cur_tile, MP_STATION) && IsStationRoadStop(cur_tile)) {
2058 RemoveRoadStop(cur_tile, flags, specindex);
2061 if (roadstopspec != nullptr) {
2062 /* Include this road stop spec's animation trigger bitmask
2063 * in the station's cached copy. */
2064 st->cached_roadstop_anim_triggers |= roadstopspec->animation.triggers;
2067 RoadStop *road_stop = new RoadStop(cur_tile);
2068 /* Insert into linked list of RoadStops. */
2069 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2070 *currstop = road_stop;
2072 if (is_truck_stop) {
2073 st->truck_station.Add(cur_tile);
2074 } else {
2075 st->bus_station.Add(cur_tile);
2078 /* Initialize an empty station. */
2079 st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
2081 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2083 RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
2084 if (is_drive_through) {
2085 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2086 * bits first. */
2087 if (IsNormalRoadTile(cur_tile)) {
2088 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
2089 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
2092 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2093 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2095 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK), road_rt, tram_rt, axis);
2096 road_stop->MakeDriveThrough();
2097 } else {
2098 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2099 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2100 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2102 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
2103 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
2104 Company::Get(st->owner)->infrastructure.station++;
2106 SetCustomRoadStopSpecIndex(cur_tile, specindex);
2107 if (roadstopspec != nullptr) {
2108 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2109 TriggerRoadStopAnimation(st, cur_tile, SAT_BUILT);
2112 MarkTileDirtyByTile(cur_tile);
2115 if (st != nullptr) {
2116 st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
2119 return cost;
2123 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
2125 if (v->type == VEH_ROAD) {
2126 /* Okay... we are a road vehicle on a drive through road stop.
2127 * But that road stop has just been removed, so we need to make
2128 * sure we are in a valid state... however, vehicles can also
2129 * turn on road stop tiles, so only clear the 'road stop' state
2130 * bits and only when the state was 'in road stop', otherwise
2131 * we'll end up clearing the turn around bits. */
2132 RoadVehicle *rv = RoadVehicle::From(v);
2133 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
2136 return nullptr;
2141 * Remove a bus station/truck stop
2142 * @param tile TileIndex been queried
2143 * @param flags operation to perform
2144 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2145 * @return cost or failure of operation
2147 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2149 Station *st = Station::GetByTile(tile);
2151 if (_current_company != OWNER_WATER) {
2152 CommandCost ret = CheckOwnership(st->owner);
2153 if (ret.Failed()) return ret;
2156 bool is_truck = IsTruckStop(tile);
2158 RoadStop **primary_stop;
2159 RoadStop *cur_stop;
2160 if (is_truck) { // truck stop
2161 primary_stop = &st->truck_stops;
2162 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
2163 } else {
2164 primary_stop = &st->bus_stops;
2165 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
2168 assert(cur_stop != nullptr);
2170 /* don't do the check for drive-through road stops when company bankrupts */
2171 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
2172 /* remove the 'going through road stop' status from all vehicles on that tile */
2173 if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
2174 } else {
2175 CommandCost ret = EnsureNoVehicleOnGround(tile);
2176 if (ret.Failed()) return ret;
2179 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2181 if (flags & DC_EXEC) {
2182 if (*primary_stop == cur_stop) {
2183 /* removed the first stop in the list */
2184 *primary_stop = cur_stop->next;
2185 /* removed the only stop? */
2186 if (*primary_stop == nullptr) {
2187 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2188 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2190 } else {
2191 /* tell the predecessor in the list to skip this stop */
2192 RoadStop *pred = *primary_stop;
2193 while (pred->next != cur_stop) pred = pred->next;
2194 pred->next = cur_stop->next;
2197 /* Update company infrastructure counts. */
2198 for (RoadTramType rtt : _roadtramtypes) {
2199 RoadType rt = GetRoadType(tile, rtt);
2200 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2203 Company::Get(st->owner)->infrastructure.station--;
2204 DirtyCompanyInfrastructureWindows(st->owner);
2206 DeleteAnimatedTile(tile);
2208 uint specindex = GetCustomRoadStopSpecIndex(tile);
2210 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2212 if (IsDriveThroughStopTile(tile)) {
2213 /* Clears the tile for us */
2214 cur_stop->ClearDriveThrough();
2215 } else {
2216 DoClearSquare(tile);
2219 delete cur_stop;
2221 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2222 * this station, then look for any currently heading to the tile. */
2223 StationID station_id = st->index;
2224 FindVehiclesWithOrder(
2225 [](const Vehicle *v) { return v->type == VEH_ROAD; },
2226 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2227 [station_id, tile](Vehicle *v) {
2228 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2229 v->SetDestTile(v->GetOrderStationLocation(station_id));
2234 st->rect.AfterRemoveTile(st, tile);
2236 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2238 st->RemoveRoadStopTileData(tile);
2239 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2241 /* Update the tile area of the truck/bus stop */
2242 if (is_truck) {
2243 st->truck_station.Clear();
2244 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2245 } else {
2246 st->bus_station.Clear();
2247 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2251 Price category = is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS;
2252 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2256 * Remove a road waypoint
2257 * @param tile TileIndex been queried
2258 * @param flags operation to perform
2259 * @param replacement_spec_index replacement spec index to avoid deallocating, if < 0, tile is not being replaced
2260 * @return cost or failure of operation
2262 CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlag flags, int replacement_spec_index)
2264 Waypoint *wp = Waypoint::GetByTile(tile);
2266 if (_current_company != OWNER_WATER) {
2267 CommandCost ret = CheckOwnership(wp->owner);
2268 if (ret.Failed()) return ret;
2271 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2272 if (!(flags & DC_BANKRUPT)) {
2273 CommandCost ret = EnsureNoVehicleOnGround(tile);
2274 if (ret.Failed()) return ret;
2277 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2279 if (flags & DC_EXEC) {
2280 /* Update company infrastructure counts. */
2281 for (RoadTramType rtt : _roadtramtypes) {
2282 RoadType rt = GetRoadType(tile, rtt);
2283 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2286 Company::Get(wp->owner)->infrastructure.station--;
2287 DirtyCompanyInfrastructureWindows(wp->owner);
2289 DeleteAnimatedTile(tile);
2291 uint specindex = GetCustomRoadStopSpecIndex(tile);
2293 DeleteNewGRFInspectWindow(GSF_ROADSTOPS, tile.base());
2295 DoClearSquare(tile);
2297 wp->rect.AfterRemoveTile(wp, tile);
2299 wp->RemoveRoadStopTileData(tile);
2300 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2302 if (replacement_spec_index < 0) {
2303 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2305 UpdateStationSignCoord(wp);
2307 /* if we deleted the whole waypoint, delete the road facility. */
2308 if (wp->road_waypoint_area.tile == INVALID_TILE) {
2309 wp->facilities &= ~(FACIL_BUS_STOP | FACIL_TRUCK_STOP);
2310 SetWindowWidgetDirty(WC_STATION_VIEW, wp->index, WID_SV_ROADVEHS);
2311 wp->UpdateVirtCoord();
2312 DeleteStationIfEmpty(wp);
2317 return CommandCost(EXPENSES_CONSTRUCTION, spec != nullptr ? spec->GetClearCost(PR_CLEAR_STATION_TRUCK) : _price[PR_CLEAR_STATION_TRUCK]);
2321 * Remove a tile area of road stop or road waypoints
2322 * @param flags operation to perform
2323 * @param roadstop_area tile area of road stop or road waypoint tiles to remove
2324 * @param station_type station type to remove
2325 * @param remove_road Remove roads of drive-through stops?
2326 * @return the cost of this operation or an error
2328 static CommandCost RemoveGenericRoadStop(DoCommandFlag flags, const TileArea &roadstop_area, StationType station_type, bool remove_road)
2330 CommandCost cost(EXPENSES_CONSTRUCTION);
2331 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2332 bool had_success = false;
2334 for (TileIndex cur_tile : roadstop_area) {
2335 /* Make sure the specified tile is a road stop of the correct type */
2336 if (!IsTileType(cur_tile, MP_STATION) || !IsAnyRoadStop(cur_tile) || GetStationType(cur_tile) != station_type) continue;
2338 /* Save information on to-be-restored roads before the stop is removed. */
2339 RoadBits road_bits = ROAD_NONE;
2340 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2341 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2342 if (IsDriveThroughStopTile(cur_tile)) {
2343 for (RoadTramType rtt : _roadtramtypes) {
2344 road_type[rtt] = GetRoadType(cur_tile, rtt);
2345 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2346 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2347 /* If we don't want to preserve our roads then restore only roads of others. */
2348 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2350 road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2353 CommandCost ret;
2354 if (station_type == STATION_ROADWAYPOINT) {
2355 ret = RemoveRoadWaypointStop(cur_tile, flags);
2356 } else {
2357 ret = RemoveRoadStop(cur_tile, flags);
2359 if (ret.Failed()) {
2360 last_error = ret;
2361 continue;
2363 cost.AddCost(ret);
2364 had_success = true;
2366 /* Restore roads. */
2367 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2368 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2369 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2371 /* Update company infrastructure counts. */
2372 int count = CountBits(road_bits);
2373 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2374 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2378 return had_success ? cost : last_error;
2382 * Remove bus or truck stops.
2383 * @param flags Operation to perform.
2384 * @param tile Northernmost tile of the removal area.
2385 * @param width Width of the removal area.
2386 * @param height Height of the removal area.
2387 * @param stop_type Type of stop (bus/truck).
2388 * @param remove_road Remove roads of drive-through stops?
2389 * @return The cost of this operation or an error.
2391 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2393 if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2394 /* Check for incorrect width / height. */
2395 if (width == 0 || height == 0) return CMD_ERROR;
2396 /* Check if the first tile and the last tile are valid */
2397 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2398 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2399 if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2401 TileArea roadstop_area(tile, width, height);
2403 return RemoveGenericRoadStop(flags, roadstop_area, stop_type == ROADSTOP_BUS ? STATION_BUS : STATION_TRUCK, remove_road);
2407 * Remove road waypoints.
2408 * @param flags operation to perform
2409 * @param start tile of road waypoint piece to remove
2410 * @param end other edge of the rect to remove
2411 * @return the cost of this operation or an error
2413 CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end)
2415 if (end == 0) end = start;
2416 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2418 TileArea roadstop_area(start, end);
2420 return RemoveGenericRoadStop(flags, roadstop_area, STATION_ROADWAYPOINT, false);
2424 * Get a possible noise reduction factor based on distance from town center.
2425 * The further you get, the less noise you generate.
2426 * So all those folks at city council can now happily slee... work in their offices
2427 * @param as airport information
2428 * @param distance minimum distance between town and airport
2429 * @return the noise that will be generated, according to distance
2431 uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2433 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2434 * So no need to go any further*/
2435 if (as->noise_level < 2) return as->noise_level;
2437 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2438 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2439 * Basically, it says that the less tolerant a town is, the bigger the distance before
2440 * an actual decrease can be granted */
2441 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2443 /* now, we want to have the distance segmented using the distance judged bareable by town
2444 * This will give us the coefficient of reduction the distance provides. */
2445 uint noise_reduction = distance / town_tolerance_distance;
2447 /* If the noise reduction equals the airport noise itself, don't give it for free.
2448 * Otherwise, simply reduce the airport's level. */
2449 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2453 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2454 * If two towns have the same distance, town with lower index is returned.
2455 * @param as airport's description
2456 * @param rotation airport's rotation
2457 * @param tile origin tile (top corner of the airport)
2458 * @param it An iterator over all airport tiles (consumed)
2459 * @param[out] mindist Minimum distance to town
2460 * @return nearest town to airport
2462 Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2464 assert(Town::GetNumItems() > 0);
2466 Town *nearest = nullptr;
2468 auto width = as->size_x;
2469 auto height = as->size_y;
2470 if (rotation == DIR_E || rotation == DIR_W) std::swap(width, height);
2472 uint perimeter_min_x = TileX(tile);
2473 uint perimeter_min_y = TileY(tile);
2474 uint perimeter_max_x = perimeter_min_x + width - 1;
2475 uint perimeter_max_y = perimeter_min_y + height - 1;
2477 mindist = UINT_MAX - 1; // prevent overflow
2479 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2480 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2481 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2482 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) {
2483 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2484 if (t == nullptr) continue;
2486 uint dist = DistanceManhattan(t->xy, cur_tile);
2487 if (dist == mindist && t->index < nearest->index) nearest = t;
2488 if (dist < mindist) {
2489 nearest = t;
2490 mindist = dist;
2495 return nearest;
2499 * Finds the town nearest to given existing airport. Based on minimal manhattan distance to any airport's tile.
2500 * If two towns have the same distance, town with lower index is returned.
2501 * @param station existing station with airport
2502 * @param[out] mindist Minimum distance to town
2503 * @return nearest town to airport
2505 static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2507 return AirportGetNearestTown(st->airport.GetSpec(), st->airport.rotation, st->airport.tile, AirportTileIterator(st), mindist);
2511 /** Recalculate the noise generated by the airports of each town */
2512 void UpdateAirportsNoise()
2514 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2516 for (const Station *st : Station::Iterate()) {
2517 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2518 uint dist;
2519 Town *nearest = AirportGetNearestTown(st, dist);
2520 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2526 * Place an Airport.
2527 * @param flags operation to perform
2528 * @param tile tile where airport will be built
2529 * @param airport_type airport type, @see airport.h
2530 * @param layout airport layout
2531 * @param station_to_join station ID to join (NEW_STATION if build new one)
2532 * @param allow_adjacent allow airports directly adjacent to other airports.
2533 * @return the cost of this operation or an error
2535 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2537 bool reuse = (station_to_join != NEW_STATION);
2538 if (!reuse) station_to_join = INVALID_STATION;
2539 bool distant_join = (station_to_join != INVALID_STATION);
2541 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2543 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2545 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2546 if (ret.Failed()) return ret;
2548 /* Check if a valid, buildable airport was chosen for construction */
2549 const AirportSpec *as = AirportSpec::Get(airport_type);
2550 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2551 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2553 Direction rotation = as->layouts[layout].rotation;
2554 int w = as->size_x;
2555 int h = as->size_y;
2556 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2557 TileArea airport_area = TileArea(tile, w, h);
2559 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2560 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2563 AirportTileTableIterator tile_iter(as->layouts[layout].tiles.data(), tile);
2564 CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2565 if (cost.Failed()) return cost;
2567 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2568 uint dist;
2569 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2570 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2572 /* Check if local auth would allow a new airport */
2573 StringID authority_refuse_message = STR_NULL;
2574 Town *authority_refuse_town = nullptr;
2576 if (_settings_game.economy.station_noise_level) {
2577 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2578 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2579 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2580 authority_refuse_town = nearest;
2582 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2583 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2584 uint num = 0;
2585 for (const Station *st : Station::Iterate()) {
2586 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2588 if (num >= 2) {
2589 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2590 authority_refuse_town = t;
2594 if (authority_refuse_message != STR_NULL) {
2595 SetDParam(0, authority_refuse_town->index);
2596 return_cmd_error(authority_refuse_message);
2599 Station *st = nullptr;
2600 ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2601 if (ret.Failed()) return ret;
2603 /* Distant join */
2604 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2606 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2607 if (ret.Failed()) return ret;
2609 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2610 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2613 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2614 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2617 if (flags & DC_EXEC) {
2618 /* Always add the noise, so there will be no need to recalculate when option toggles */
2619 nearest->noise_reached += newnoise_level;
2621 st->AddFacility(FACIL_AIRPORT, tile);
2622 st->airport.type = airport_type;
2623 st->airport.layout = layout;
2624 st->airport.flags = 0;
2625 st->airport.rotation = rotation;
2627 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2629 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2630 Tile t(iter);
2631 MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2632 SetStationTileRandomBits(t, GB(Random(), 0, 4));
2633 st->airport.Add(iter);
2635 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(t);
2638 /* Only call the animation trigger after all tiles have been built */
2639 for (AirportTileTableIterator iter(as->layouts[layout].tiles.data(), tile); iter != INVALID_TILE; ++iter) {
2640 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2643 UpdateAirplanesOnNewStation(st);
2645 Company::Get(st->owner)->infrastructure.airport++;
2647 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2648 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2650 if (_settings_game.economy.station_noise_level) {
2651 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2655 return cost;
2659 * Remove an airport
2660 * @param tile TileIndex been queried
2661 * @param flags operation to perform
2662 * @return cost or failure of operation
2664 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2666 Station *st = Station::GetByTile(tile);
2668 if (_current_company != OWNER_WATER) {
2669 CommandCost ret = CheckOwnership(st->owner);
2670 if (ret.Failed()) return ret;
2673 tile = st->airport.tile;
2675 CommandCost cost(EXPENSES_CONSTRUCTION);
2677 for (const Aircraft *a : Aircraft::Iterate()) {
2678 if (!a->IsNormalAircraft()) continue;
2679 if (a->targetairport == st->index && a->state != FLYING) {
2680 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2684 if (flags & DC_EXEC) {
2685 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2686 TileIndex tile_cur = st->airport.GetHangarTile(i);
2687 OrderBackup::Reset(tile_cur, false);
2688 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2691 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2692 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2693 * need of recalculation */
2694 uint dist;
2695 Town *nearest = AirportGetNearestTown(st, dist);
2696 nearest->noise_reached -= GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2698 if (_settings_game.economy.station_noise_level) {
2699 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2703 for (TileIndex tile_cur : st->airport) {
2704 if (!st->TileBelongsToAirport(tile_cur)) continue;
2706 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2707 if (ret.Failed()) return ret;
2709 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2711 if (flags & DC_EXEC) {
2712 DeleteAnimatedTile(tile_cur);
2713 DoClearSquare(tile_cur);
2714 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur.base());
2718 if (flags & DC_EXEC) {
2719 /* Clear the persistent storage. */
2720 delete st->airport.psa;
2722 st->rect.AfterRemoveRect(st, st->airport);
2724 st->airport.Clear();
2725 st->facilities &= ~FACIL_AIRPORT;
2726 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2728 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2730 Company::Get(st->owner)->infrastructure.airport--;
2732 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2734 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2737 return cost;
2741 * Open/close an airport to incoming aircraft.
2742 * @param flags Operation to perform.
2743 * @param station_id Station ID of the airport.
2744 * @return the cost of this operation or an error
2746 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2748 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2749 Station *st = Station::Get(station_id);
2751 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2753 CommandCost ret = CheckOwnership(st->owner);
2754 if (ret.Failed()) return ret;
2756 if (flags & DC_EXEC) {
2757 st->airport.flags ^= AIRPORT_CLOSED_block;
2758 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2760 return CommandCost();
2764 * Tests whether the company's vehicles have this station in orders
2765 * @param station station ID
2766 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2767 * @param company company ID
2769 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2771 for (const OrderList *orderlist : OrderList::Iterate()) {
2772 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2773 assert(v != nullptr);
2774 if ((v->owner == company) != include_company) continue;
2776 for (const Order *order = orderlist->GetFirstOrder(); order != nullptr; order = order->next) {
2777 if (order->GetDestination() == station && (order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT))) {
2778 return true;
2782 return false;
2785 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2786 {-1, 0},
2787 { 0, 0},
2788 { 0, 0},
2789 { 0, -1}
2791 static const uint8_t _dock_w_chk[4] = { 2, 1, 2, 1 };
2792 static const uint8_t _dock_h_chk[4] = { 1, 2, 1, 2 };
2795 * Build a dock/haven.
2796 * @param flags operation to perform
2797 * @param tile tile where dock will be built
2798 * @param station_to_join station ID to join (NEW_STATION if build new one)
2799 * @param adjacent allow docks directly adjacent to other docks.
2800 * @return the cost of this operation or an error
2802 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2804 bool reuse = (station_to_join != NEW_STATION);
2805 if (!reuse) station_to_join = INVALID_STATION;
2806 bool distant_join = (station_to_join != INVALID_STATION);
2808 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2810 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2811 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2812 direction = ReverseDiagDir(direction);
2814 /* Docks cannot be placed on rapids */
2815 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2817 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2818 if (ret.Failed()) return ret;
2820 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2822 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2823 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2824 if (ret.Failed()) return ret;
2825 cost.AddCost(ret);
2827 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2829 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2830 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2833 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2835 /* Get the water class of the water tile before it is cleared.*/
2836 WaterClass wc = GetWaterClass(tile_cur);
2838 bool add_cost = !IsWaterTile(tile_cur);
2839 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2840 if (ret.Failed()) return ret;
2841 if (add_cost) cost.AddCost(ret);
2843 tile_cur += TileOffsByDiagDir(direction);
2844 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2845 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2848 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2849 _dock_w_chk[direction], _dock_h_chk[direction]);
2851 /* middle */
2852 Station *st = nullptr;
2853 ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2854 if (ret.Failed()) return ret;
2856 /* Distant join */
2857 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2859 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2860 if (ret.Failed()) return ret;
2862 if (flags & DC_EXEC) {
2863 st->ship_station.Add(tile);
2864 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2865 st->ship_station.Add(flat_tile);
2866 st->AddFacility(FACIL_DOCK, tile);
2868 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2870 /* If the water part of the dock is on a canal, update infrastructure counts.
2871 * This is needed as we've cleared that tile before.
2872 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2873 * See: MakeWaterKeepingClass() */
2874 if (wc == WATER_CLASS_CANAL && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WATER_CLASS_CANAL && IsTileOwner(flat_tile, _current_company))) {
2875 Company::Get(st->owner)->infrastructure.water++;
2877 Company::Get(st->owner)->infrastructure.station += 2;
2879 MakeDock(tile, st->owner, st->index, direction, wc);
2880 UpdateStationDockingTiles(st);
2882 st->AfterStationTileSetChange(true, STATION_DOCK);
2885 return cost;
2888 void RemoveDockingTile(TileIndex t)
2890 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2891 TileIndex tile = t + TileOffsByDiagDir(d);
2892 if (!IsValidTile(tile)) continue;
2894 if (IsTileType(tile, MP_STATION)) {
2895 Station *st = Station::GetByTile(tile);
2896 if (st != nullptr) UpdateStationDockingTiles(st);
2897 } else if (IsTileType(tile, MP_INDUSTRY)) {
2898 Station *neutral = Industry::GetByTile(tile)->neutral_station;
2899 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2905 * Clear docking tile status from tiles around a removed dock, if the tile has
2906 * no neighbours which would keep it as a docking tile.
2907 * @param tile Ex-dock tile to check.
2909 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2911 assert(IsValidTile(tile));
2913 /* Clear and maybe re-set docking tile */
2914 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2915 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2916 if (!IsValidTile(docking_tile)) continue;
2918 if (IsPossibleDockingTile(docking_tile)) {
2919 SetDockingTile(docking_tile, false);
2920 CheckForDockingTile(docking_tile);
2926 * Find the part of a dock that is land-based
2927 * @param t Dock tile to find land part of
2928 * @return tile of land part of dock
2930 static TileIndex FindDockLandPart(TileIndex t)
2932 assert(IsDockTile(t));
2934 StationGfx gfx = GetStationGfx(t);
2935 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2937 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2938 TileIndex tile = t + TileOffsByDiagDir(d);
2939 if (!IsValidTile(tile)) continue;
2940 if (!IsDockTile(tile)) continue;
2941 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2944 return INVALID_TILE;
2948 * Remove a dock
2949 * @param tile TileIndex been queried
2950 * @param flags operation to perform
2951 * @return cost or failure of operation
2953 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2955 Station *st = Station::GetByTile(tile);
2956 CommandCost ret = CheckOwnership(st->owner);
2957 if (ret.Failed()) return ret;
2959 if (!IsDockTile(tile)) return CMD_ERROR;
2961 TileIndex tile1 = FindDockLandPart(tile);
2962 if (tile1 == INVALID_TILE) return CMD_ERROR;
2963 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2965 ret = EnsureNoVehicleOnGround(tile1);
2966 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2967 if (ret.Failed()) return ret;
2969 if (flags & DC_EXEC) {
2970 DoClearSquare(tile1);
2971 MarkTileDirtyByTile(tile1);
2972 MakeWaterKeepingClass(tile2, st->owner);
2974 st->rect.AfterRemoveTile(st, tile1);
2975 st->rect.AfterRemoveTile(st, tile2);
2977 MakeShipStationAreaSmaller(st);
2978 if (st->ship_station.tile == INVALID_TILE) {
2979 st->ship_station.Clear();
2980 st->docking_station.Clear();
2981 st->facilities &= ~FACIL_DOCK;
2982 SetWindowClassesDirty(WC_VEHICLE_ORDERS);
2985 Company::Get(st->owner)->infrastructure.station -= 2;
2987 st->AfterStationTileSetChange(false, STATION_DOCK);
2989 ClearDockingTilesCheckingNeighbours(tile1);
2990 ClearDockingTilesCheckingNeighbours(tile2);
2992 for (Ship *s : Ship::Iterate()) {
2993 /* Find all ships going to our dock. */
2994 if (s->current_order.GetDestination() != st->index) {
2995 continue;
2998 /* Find ships that are marked as "loading" but are no longer on a
2999 * docking tile. Force them to leave the station (as they were loading
3000 * on the removed dock). */
3001 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3002 s->LeaveStation();
3005 /* If we no longer have a dock, mark the order as invalid and send
3006 * the ship to the next order (or, if there is none, make it
3007 * wander the world). */
3008 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
3009 s->SetDestTile(s->GetOrderStationLocation(st->index));
3014 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
3017 #include "table/station_land.h"
3020 * Get station tile layout for a station type and its station gfx.
3021 * @param st Station type to draw.
3022 * @param gfx StationGfx of tile to draw.
3023 * @return Tile layout to draw.
3025 const DrawTileSprites *GetStationTileLayout(StationType st, uint8_t gfx)
3027 const auto &layouts = _station_display_datas[st];
3028 if (gfx >= layouts.size()) gfx &= 1;
3029 return layouts.data() + gfx;
3033 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
3034 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
3035 * is set to the overlay to draw.
3036 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
3037 * @param[in,out] ground Groundsprite to draw.
3038 * @param[out] overlay_offset Overlay to draw.
3039 * @return true if overlay can be drawn.
3041 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3043 bool snow_desert;
3044 switch (*ground) {
3045 case SPR_RAIL_TRACK_X:
3046 case SPR_MONO_TRACK_X:
3047 case SPR_MGLV_TRACK_X:
3048 snow_desert = false;
3049 *overlay_offset = RTO_X;
3050 break;
3052 case SPR_RAIL_TRACK_Y:
3053 case SPR_MONO_TRACK_Y:
3054 case SPR_MGLV_TRACK_Y:
3055 snow_desert = false;
3056 *overlay_offset = RTO_Y;
3057 break;
3059 case SPR_RAIL_TRACK_X_SNOW:
3060 case SPR_MONO_TRACK_X_SNOW:
3061 case SPR_MGLV_TRACK_X_SNOW:
3062 snow_desert = true;
3063 *overlay_offset = RTO_X;
3064 break;
3066 case SPR_RAIL_TRACK_Y_SNOW:
3067 case SPR_MONO_TRACK_Y_SNOW:
3068 case SPR_MGLV_TRACK_Y_SNOW:
3069 snow_desert = true;
3070 *overlay_offset = RTO_Y;
3071 break;
3073 default:
3074 return false;
3077 if (ti != nullptr) {
3078 /* Decide snow/desert from tile */
3079 switch (_settings_game.game_creation.landscape) {
3080 case LT_ARCTIC:
3081 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3082 break;
3084 case LT_TROPIC:
3085 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
3086 break;
3088 default:
3089 break;
3093 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3094 return true;
3097 static void DrawTile_Station(TileInfo *ti)
3099 const NewGRFSpriteLayout *layout = nullptr;
3100 DrawTileSprites tmp_rail_layout;
3101 const DrawTileSprites *t = nullptr;
3102 int32_t total_offset;
3103 const RailTypeInfo *rti = nullptr;
3104 uint32_t relocation = 0;
3105 uint32_t ground_relocation = 0;
3106 BaseStation *st = nullptr;
3107 const StationSpec *statspec = nullptr;
3108 uint tile_layout = 0;
3110 if (HasStationRail(ti->tile)) {
3111 rti = GetRailTypeInfo(GetRailType(ti->tile));
3112 total_offset = rti->GetRailtypeSpriteOffset();
3114 if (IsCustomStationSpecIndex(ti->tile)) {
3115 /* look for customization */
3116 st = BaseStation::GetByTile(ti->tile);
3117 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3119 if (statspec != nullptr) {
3120 tile_layout = GetStationGfx(ti->tile);
3122 if (HasBit(statspec->callback_mask, CBM_STATION_DRAW_TILE_LAYOUT)) {
3123 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3124 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
3127 /* Ensure the chosen tile layout is valid for this custom station */
3128 if (!statspec->renderdata.empty()) {
3129 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3130 if (!layout->NeedsPreprocessing()) {
3131 t = layout;
3132 layout = nullptr;
3137 } else {
3138 total_offset = 0;
3141 StationGfx gfx = GetStationGfx(ti->tile);
3142 if (IsAirport(ti->tile)) {
3143 gfx = GetAirportGfx(ti->tile);
3144 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3145 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3146 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3147 return;
3149 /* No sprite group (or no valid one) found, meaning no graphics associated.
3150 * Use the substitute one instead */
3151 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3152 gfx = ats->grf_prop.subst_id;
3154 switch (gfx) {
3155 case APT_RADAR_GRASS_FENCE_SW:
3156 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3157 break;
3158 case APT_GRASS_FENCE_NE_FLAG:
3159 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3160 break;
3161 case APT_RADAR_FENCE_SW:
3162 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3163 break;
3164 case APT_RADAR_FENCE_NE:
3165 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3166 break;
3167 case APT_GRASS_FENCE_NE_FLAG_2:
3168 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3169 break;
3173 Owner owner = GetTileOwner(ti->tile);
3175 PaletteID palette;
3176 if (Company::IsValidID(owner)) {
3177 palette = COMPANY_SPRITE_COLOUR(owner);
3178 } else {
3179 /* Some stations are not owner by a company, namely oil rigs */
3180 palette = PALETTE_TO_GREY;
3183 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3185 /* don't show foundation for docks */
3186 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3187 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
3188 /* Station has custom foundations.
3189 * Check whether the foundation continues beyond the tile's upper sides. */
3190 uint edge_info = 0;
3191 auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3192 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3193 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3194 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
3195 if (image == 0) goto draw_default_foundation;
3197 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
3198 /* Station provides extended foundations. */
3200 static const uint8_t foundation_parts[] = {
3201 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3202 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3203 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3204 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3207 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3208 } else {
3209 /* Draw simple foundations, built up from 8 possible foundation sprites. */
3211 /* Each set bit represents one of the eight composite sprites to be drawn.
3212 * 'Invalid' entries will not drawn but are included for completeness. */
3213 static const uint8_t composite_foundation_parts[] = {
3214 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
3215 0x00, 0xD1, 0xE4, 0xE0,
3216 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
3217 0xCA, 0xC9, 0xC4, 0xC0,
3218 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
3219 0xD2, 0x91, 0xE4, 0xA0,
3220 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
3221 0x4A, 0x09, 0x44
3224 uint8_t parts = composite_foundation_parts[ti->tileh];
3226 /* If foundations continue beyond the tile's upper sides then
3227 * mask out the last two pieces. */
3228 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3229 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3231 if (parts == 0) {
3232 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
3233 * correct offset for the childsprites.
3234 * So, draw the (completely empty) sprite of the default foundations. */
3235 goto draw_default_foundation;
3238 StartSpriteCombine();
3239 for (int i = 0; i < 8; i++) {
3240 if (HasBit(parts, i)) {
3241 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
3244 EndSpriteCombine();
3247 OffsetGroundSprite(0, -8);
3248 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, ti->tileh);
3249 } else {
3250 draw_default_foundation:
3251 DrawFoundation(ti, FOUNDATION_LEVELED);
3255 bool draw_ground = false;
3257 if (IsBuoy(ti->tile)) {
3258 DrawWaterClassGround(ti);
3259 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3260 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3261 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3262 if (ti->tileh == SLOPE_FLAT) {
3263 DrawWaterClassGround(ti);
3264 } else {
3265 assert(IsDock(ti->tile));
3266 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3267 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
3268 if (wc == WATER_CLASS_SEA) {
3269 DrawShoreTile(ti->tileh);
3270 } else {
3271 DrawClearLandTile(ti, 3);
3274 } else if (IsRoadWaypointTile(ti->tile)) {
3275 RoadBits bits = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? ROAD_X : ROAD_Y;
3276 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3277 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3278 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3279 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : ROAD_NONE;
3280 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3281 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3283 if (ti->tileh != SLOPE_FLAT) {
3284 DrawFoundation(ti, FOUNDATION_LEVELED);
3287 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3288 } else {
3289 if (layout != nullptr) {
3290 /* Sprite layout which needs preprocessing */
3291 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
3292 uint32_t var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3293 for (uint8_t var10 : SetBitIterator(var10_values)) {
3294 uint32_t var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
3295 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
3297 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
3298 t = &tmp_rail_layout;
3299 total_offset = 0;
3300 } else if (statspec != nullptr) {
3301 /* Simple sprite layout */
3302 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3303 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
3304 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3306 ground_relocation += rti->fallback_railtype;
3309 draw_ground = true;
3312 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3313 SpriteID image = t->ground.sprite;
3314 PaletteID pal = t->ground.pal;
3315 RailTrackOffset overlay_offset;
3316 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3317 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
3318 DrawGroundSprite(image, PAL_NONE);
3319 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3321 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3322 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
3323 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3325 } else {
3326 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3327 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3328 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3330 /* PBS debugging, draw reserved tracks darker */
3331 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3332 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
3337 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
3339 if (IsAnyRoadStop(ti->tile)) {
3340 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3341 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3342 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3343 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3345 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3346 DiagDirection dir = GetRoadStopDir(ti->tile);
3347 StationType type = GetStationType(ti->tile);
3349 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3350 RoadStopDrawMode stop_draw_mode{};
3351 if (stopspec != nullptr) {
3352 stop_draw_mode = stopspec->draw_mode;
3353 int view = dir;
3354 if (IsDriveThroughStopTile(ti->tile)) view += 4;
3355 st = BaseStation::GetByTile(ti->tile);
3356 RoadStopResolverObject object(stopspec, st, ti->tile, INVALID_ROADTYPE, type, view);
3357 const SpriteGroup *group = object.Resolve();
3358 if (group != nullptr && group->type == SGT_TILELAYOUT) {
3359 if (HasBit(stopspec->flags, RSF_DRAW_MODE_REGISTER)) {
3360 stop_draw_mode = static_cast<RoadStopDrawMode>(GetRegister(0x100));
3362 if (type == STATION_ROADWAYPOINT && (stop_draw_mode & ROADSTOP_DRAW_MODE_WAYP_GROUND)) {
3363 draw_ground = true;
3365 t = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
3369 /* Draw ground sprite */
3370 if (draw_ground) {
3371 SpriteID image = t->ground.sprite;
3372 PaletteID pal = t->ground.pal;
3373 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3374 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3375 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3376 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3380 if (IsDriveThroughStopTile(ti->tile)) {
3381 if (type != STATION_ROADWAYPOINT && (stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_OVERLAY) != 0)) {
3382 uint sprite_offset = axis == AXIS_X ? 1 : 0;
3383 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3385 } else {
3386 /* Non-drivethrough road stops are only valid for roads. */
3387 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3389 if ((stopspec == nullptr || (stop_draw_mode & ROADSTOP_DRAW_MODE_ROAD) != 0) && road_rti->UsesOverlay()) {
3390 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3391 DrawGroundSprite(ground + dir, PAL_NONE);
3395 if (stopspec == nullptr || !HasBit(stopspec->flags, RSF_NO_CATENARY)) {
3396 /* Draw road, tram catenary */
3397 DrawRoadCatenary(ti);
3401 if (IsRailWaypoint(ti->tile)) {
3402 /* Don't offset the waypoint graphics; they're always the same. */
3403 total_offset = 0;
3406 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3409 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3411 int32_t total_offset = 0;
3412 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3413 const DrawTileSprites *t = GetStationTileLayout(st, image);
3414 const RailTypeInfo *railtype_info = nullptr;
3416 if (railtype != INVALID_RAILTYPE) {
3417 railtype_info = GetRailTypeInfo(railtype);
3418 total_offset = railtype_info->GetRailtypeSpriteOffset();
3421 SpriteID img = t->ground.sprite;
3422 RailTrackOffset overlay_offset;
3423 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3424 SpriteID ground = GetCustomRailSprite(railtype_info, INVALID_TILE, RTSG_GROUND);
3425 DrawSprite(img, PAL_NONE, x, y);
3426 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3427 } else {
3428 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3431 if (roadtype != INVALID_ROADTYPE) {
3432 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3433 if (image >= 4) {
3434 /* Drive-through stop */
3435 uint sprite_offset = 5 - image;
3437 /* Road underlay takes precedence over tram */
3438 if (roadtype_info->UsesOverlay()) {
3439 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_GROUND);
3440 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3442 SpriteID overlay = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_OVERLAY);
3443 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3444 } else if (RoadTypeIsTram(roadtype)) {
3445 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3447 } else {
3448 /* Bay stop */
3449 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3450 SpriteID ground = GetCustomRoadSprite(roadtype_info, INVALID_TILE, ROTSG_ROADSTOP);
3451 DrawSprite(ground + image, PAL_NONE, x, y);
3456 /* Default waypoint has no railtype specific sprites */
3457 DrawRailTileSeqInGUI(x, y, t, (st == STATION_WAYPOINT || st == STATION_ROADWAYPOINT) ? 0 : total_offset, 0, pal);
3460 static int GetSlopePixelZ_Station(TileIndex tile, uint, uint, bool)
3462 return GetTileMaxPixelZ(tile);
3465 static Foundation GetFoundation_Station(TileIndex, Slope tileh)
3467 return FlatteningFoundation(tileh);
3470 static void FillTileDescRoadStop(TileIndex tile, TileDesc *td)
3472 RoadType road_rt = GetRoadTypeRoad(tile);
3473 RoadType tram_rt = GetRoadTypeTram(tile);
3474 Owner road_owner = INVALID_OWNER;
3475 Owner tram_owner = INVALID_OWNER;
3476 if (road_rt != INVALID_ROADTYPE) {
3477 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3478 td->roadtype = rti->strings.name;
3479 td->road_speed = rti->max_speed / 2;
3480 road_owner = GetRoadOwner(tile, RTT_ROAD);
3483 if (tram_rt != INVALID_ROADTYPE) {
3484 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3485 td->tramtype = rti->strings.name;
3486 td->tram_speed = rti->max_speed / 2;
3487 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3490 if (IsDriveThroughStopTile(tile)) {
3491 /* Is there a mix of owners? */
3492 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3493 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3494 uint i = 1;
3495 if (road_owner != INVALID_OWNER) {
3496 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3497 td->owner[i] = road_owner;
3498 i++;
3500 if (tram_owner != INVALID_OWNER) {
3501 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3502 td->owner[i] = tram_owner;
3508 void FillTileDescRailStation(TileIndex tile, TileDesc *td)
3510 const StationSpec *spec = GetStationSpec(tile);
3512 if (spec != nullptr) {
3513 td->station_class = StationClass::Get(spec->class_index)->name;
3514 td->station_name = spec->name;
3516 if (spec->grf_prop.grffile != nullptr) {
3517 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3518 td->grf = gc->GetName();
3522 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3523 td->rail_speed = rti->max_speed;
3524 td->railtype = rti->strings.name;
3527 void FillTileDescAirport(TileIndex tile, TileDesc *td)
3529 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3530 td->airport_class = AirportClass::Get(as->class_index)->name;
3531 td->airport_name = as->name;
3533 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3534 td->airport_tile_name = ats->name;
3536 if (as->grf_prop.grffile != nullptr) {
3537 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3538 td->grf = gc->GetName();
3539 } else if (ats->grf_prop.grffile != nullptr) {
3540 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3541 td->grf = gc->GetName();
3545 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3547 td->owner[0] = GetTileOwner(tile);
3548 td->build_date = BaseStation::GetByTile(tile)->build_date;
3550 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3551 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3552 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3554 StringID str;
3555 switch (GetStationType(tile)) {
3556 default: NOT_REACHED();
3557 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3558 case STATION_AIRPORT:
3559 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3560 break;
3561 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3562 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3563 case STATION_OILRIG: {
3564 const Industry *i = Station::GetByTile(tile)->industry;
3565 const IndustrySpec *is = GetIndustrySpec(i->type);
3566 td->owner[0] = i->owner;
3567 str = is->name;
3568 if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3569 break;
3571 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3572 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3573 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3574 case STATION_ROADWAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3576 td->str = str;
3580 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3582 TrackBits trackbits = TRACK_BIT_NONE;
3584 switch (mode) {
3585 case TRANSPORT_RAIL:
3586 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3587 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3589 break;
3591 case TRANSPORT_WATER:
3592 /* buoy is coded as a station, it is always on open water */
3593 if (IsBuoy(tile)) {
3594 trackbits = TRACK_BIT_ALL;
3595 /* remove tracks that connect NE map edge */
3596 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3597 /* remove tracks that connect NW map edge */
3598 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3600 break;
3602 case TRANSPORT_ROAD:
3603 if (IsAnyRoadStop(tile)) {
3604 RoadTramType rtt = (RoadTramType)sub_mode;
3605 if (!HasTileRoadType(tile, rtt)) break;
3607 DiagDirection dir = GetRoadStopDir(tile);
3608 Axis axis = DiagDirToAxis(dir);
3610 if (side != INVALID_DIAGDIR) {
3611 if (axis != DiagDirToAxis(side) || (IsBayRoadStopTile(tile) && dir != side)) break;
3614 trackbits = AxisToTrackBits(axis);
3616 break;
3618 default:
3619 break;
3622 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3626 static void TileLoop_Station(TileIndex tile)
3628 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3629 * hardcoded.....not good */
3630 switch (GetStationType(tile)) {
3631 case STATION_AIRPORT:
3632 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3633 break;
3635 case STATION_DOCK:
3636 if (!IsTileFlat(tile)) break; // only handle water part
3637 [[fallthrough]];
3639 case STATION_OILRIG: //(station part)
3640 case STATION_BUOY:
3641 TileLoop_Water(tile);
3642 break;
3644 case STATION_ROADWAYPOINT: {
3645 switch (_settings_game.game_creation.landscape) {
3646 case LT_ARCTIC:
3647 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3648 ToggleRoadWaypointOnSnowOrDesert(tile);
3649 MarkTileDirtyByTile(tile);
3651 break;
3653 case LT_TROPIC:
3654 if (GetTropicZone(tile) == TROPICZONE_DESERT && !IsRoadWaypointOnSnowOrDesert(tile)) {
3655 ToggleRoadWaypointOnSnowOrDesert(tile);
3656 MarkTileDirtyByTile(tile);
3658 break;
3660 default: break;
3663 HouseZonesBits new_zone = HZB_TOWN_EDGE;
3664 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3665 if (t != nullptr) {
3666 new_zone = GetTownRadiusGroup(t, tile);
3669 /* Adjust road ground type depending on 'new_zone' */
3670 Roadside new_rs = new_zone > HZB_TOWN_EDGE ? ROADSIDE_PAVED : ROADSIDE_GRASS;
3671 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3673 if (new_rs != cur_rs) {
3674 SetRoadWaypointRoadside(tile, cur_rs == ROADSIDE_BARREN ? new_rs : ROADSIDE_BARREN);
3675 MarkTileDirtyByTile(tile);
3677 break;
3680 default: break;
3685 static void AnimateTile_Station(TileIndex tile)
3687 if (HasStationRail(tile)) {
3688 AnimateStationTile(tile);
3689 return;
3692 if (IsAirport(tile)) {
3693 AnimateAirportTile(tile);
3694 return;
3697 if (IsAnyRoadStopTile(tile)) {
3698 AnimateRoadStopTile(tile);
3699 return;
3704 static bool ClickTile_Station(TileIndex tile)
3706 const BaseStation *bst = BaseStation::GetByTile(tile);
3708 if (bst->facilities & FACIL_WAYPOINT) {
3709 ShowWaypointWindow(Waypoint::From(bst));
3710 } else if (IsHangar(tile)) {
3711 const Station *st = Station::From(bst);
3712 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3713 } else {
3714 ShowStationViewWindow(bst->index);
3716 return true;
3719 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3721 if (v->type == VEH_TRAIN) {
3722 StationID station_id = GetStationIndex(tile);
3723 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3724 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3726 int station_ahead;
3727 int station_length;
3728 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3730 /* Stop whenever that amount of station ahead + the distance from the
3731 * begin of the platform to the stop location is longer than the length
3732 * of the platform. Station ahead 'includes' the current tile where the
3733 * vehicle is on, so we need to subtract that. */
3734 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3736 DiagDirection dir = DirToDiagDir(v->direction);
3738 x &= 0xF;
3739 y &= 0xF;
3741 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3742 if (y == TILE_SIZE / 2) {
3743 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3744 stop &= TILE_SIZE - 1;
3746 if (x == stop) {
3747 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3748 } else if (x < stop) {
3749 v->vehstatus |= VS_TRAIN_SLOWING;
3750 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3751 if (spd < v->cur_speed) v->cur_speed = spd;
3754 } else if (v->type == VEH_ROAD) {
3755 RoadVehicle *rv = RoadVehicle::From(v);
3756 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3757 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3758 /* Attempt to allocate a parking bay in a road stop */
3759 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3764 return VETSB_CONTINUE;
3768 * Run the watched cargo callback for all houses in the catchment area.
3769 * @param st Station.
3771 void TriggerWatchedCargoCallbacks(Station *st)
3773 /* Collect cargoes accepted since the last big tick. */
3774 CargoTypes cargoes = 0;
3775 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3776 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3779 /* Anything to do? */
3780 if (cargoes == 0) return;
3782 /* Loop over all houses in the catchment. */
3783 BitmapTileIterator it(st->catchment_tiles);
3784 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3785 if (IsTileType(tile, MP_HOUSE)) {
3786 WatchedCargoCallback(tile, cargoes);
3792 * This function is called for each station once every 250 ticks.
3793 * Not all stations will get the tick at the same time.
3794 * @param st the station receiving the tick.
3795 * @return true if the station is still valid (wasn't deleted)
3797 static bool StationHandleBigTick(BaseStation *st)
3799 if (!st->IsInUse()) {
3800 if (++st->delete_ctr >= 8) delete st;
3801 return false;
3804 if (Station::IsExpected(st)) {
3805 TriggerWatchedCargoCallbacks(Station::From(st));
3807 for (GoodsEntry &ge : Station::From(st)->goods) {
3808 ClrBit(ge.status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3813 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3815 return true;
3818 static inline void byte_inc_sat(uint8_t *p)
3820 uint8_t b = *p + 1;
3821 if (b != 0) *p = b;
3825 * Truncate the cargo by a specific amount.
3826 * @param cs The type of cargo to perform the truncation for.
3827 * @param ge The goods entry, of the station, to truncate.
3828 * @param amount The amount to truncate the cargo by.
3830 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3832 /* If truncating also punish the source stations' ratings to
3833 * decrease the flow of incoming cargo. */
3835 StationCargoAmountMap waiting_per_source;
3836 ge->cargo.Truncate(amount, &waiting_per_source);
3837 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3838 Station *source_station = Station::GetIfValid(i->first);
3839 if (source_station == nullptr) continue;
3841 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3842 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3846 static void UpdateStationRating(Station *st)
3848 bool waiting_changed = false;
3850 byte_inc_sat(&st->time_since_load);
3851 byte_inc_sat(&st->time_since_unload);
3853 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3854 GoodsEntry *ge = &st->goods[cs->Index()];
3855 /* Slowly increase the rating back to its original level in the case we
3856 * didn't deliver cargo yet to this station. This happens when a bribe
3857 * failed while you didn't moved that cargo yet to a station. */
3858 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3859 ge->rating++;
3862 /* Only change the rating if we are moving this cargo */
3863 if (ge->HasRating()) {
3864 byte_inc_sat(&ge->time_since_pickup);
3865 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3866 ClrBit(ge->status, GoodsEntry::GES_RATING);
3867 ge->last_speed = 0;
3868 TruncateCargo(cs, ge);
3869 waiting_changed = true;
3870 continue;
3873 bool skip = false;
3874 int rating = 0;
3875 uint waiting = ge->cargo.AvailableCount();
3877 /* num_dests is at least 1 if there is any cargo as
3878 * INVALID_STATION is also a destination.
3880 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3882 /* Average amount of cargo per next hop, but prefer solitary stations
3883 * with only one or two next hops. They are allowed to have more
3884 * cargo waiting per next hop.
3885 * With manual cargo distribution waiting_avg = waiting / 2 as then
3886 * INVALID_STATION is the only destination.
3888 uint waiting_avg = waiting / (num_dests + 1);
3890 if (_cheats.station_rating.value) {
3891 ge->rating = rating = MAX_STATION_RATING;
3892 skip = true;
3893 } else if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3894 /* Perform custom station rating. If it succeeds the speed, days in transit and
3895 * waiting cargo ratings must not be executed. */
3897 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3898 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3900 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
3901 | (ClampTo<uint16_t>(ge->max_waiting_cargo) << 8)
3902 | (ClampTo<uint8_t>(last_speed) << 24);
3903 /* Convert to the 'old' vehicle types */
3904 uint32_t var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3905 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3906 if (callback != CALLBACK_FAILED) {
3907 skip = true;
3908 rating = GB(callback, 0, 14);
3910 /* Simulate a 15 bit signed value */
3911 if (HasBit(callback, 14)) rating -= 0x4000;
3915 if (!skip) {
3916 int b = ge->last_speed - 85;
3917 if (b >= 0) rating += b >> 2;
3919 uint8_t waittime = ge->time_since_pickup;
3920 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3921 if (waittime <= 21) rating += 25;
3922 if (waittime <= 12) rating += 25;
3923 if (waittime <= 6) rating += 45;
3924 if (waittime <= 3) rating += 35;
3926 rating -= 90;
3927 if (ge->max_waiting_cargo <= 1500) rating += 55;
3928 if (ge->max_waiting_cargo <= 1000) rating += 35;
3929 if (ge->max_waiting_cargo <= 600) rating += 10;
3930 if (ge->max_waiting_cargo <= 300) rating += 20;
3931 if (ge->max_waiting_cargo <= 100) rating += 10;
3934 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3936 uint8_t age = ge->last_age;
3937 if (age < 3) rating += 10;
3938 if (age < 2) rating += 10;
3939 if (age < 1) rating += 13;
3942 int or_ = ge->rating; // old rating
3944 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3945 ge->rating = rating = or_ + Clamp(ClampTo<uint8_t>(rating) - or_, -2, 2);
3947 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3948 * remove some random amount of goods from the station */
3949 if (rating <= 64 && waiting_avg >= 100) {
3950 int dec = Random() & 0x1F;
3951 if (waiting_avg < 200) dec &= 7;
3952 waiting -= (dec + 1) * num_dests;
3953 waiting_changed = true;
3956 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3957 if (rating <= 127 && waiting != 0) {
3958 uint32_t r = Random();
3959 if (rating <= (int)GB(r, 0, 7)) {
3960 /* Need to have int, otherwise it will just overflow etc. */
3961 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3962 waiting_changed = true;
3966 /* At some point we really must cap the cargo. Previously this
3967 * was a strict 4095, but now we'll have a less strict, but
3968 * increasingly aggressive truncation of the amount of cargo. */
3969 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3970 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3971 static const uint MAX_WAITING_CARGO = 1 << 15;
3973 if (waiting > WAITING_CARGO_THRESHOLD) {
3974 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3975 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3977 waiting = std::min(waiting, MAX_WAITING_CARGO);
3978 waiting_changed = true;
3981 /* We can't truncate cargo that's already reserved for loading.
3982 * Thus StoredCount() here. */
3983 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3984 /* Feed back the exact own waiting cargo at this station for the
3985 * next rating calculation. */
3986 ge->max_waiting_cargo = 0;
3988 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3989 } else {
3990 /* If the average number per next hop is low, be more forgiving. */
3991 ge->max_waiting_cargo = waiting_avg;
3997 StationID index = st->index;
3998 if (waiting_changed) {
3999 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
4000 } else {
4001 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4006 * Reroute cargo of type c at station st or in any vehicles unloading there.
4007 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
4008 * @param st Station to be rerouted at.
4009 * @param c Type of cargo.
4010 * @param avoid Original next hop of cargo, avoid this.
4011 * @param avoid2 Another station to be avoided when rerouting.
4013 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
4015 GoodsEntry &ge = st->goods[c];
4017 /* Reroute cargo in station. */
4018 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
4020 /* Reroute cargo staged to be transferred. */
4021 for (Vehicle *v : st->loading_vehicles) {
4022 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4023 if (u->cargo_type != c) continue;
4024 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4030 * Check all next hops of cargo packets in this station for existence of a
4031 * a valid link they may use to travel on. Reroute any cargo not having a valid
4032 * link and remove timed out links found like this from the linkgraph. We're
4033 * not all links here as that is expensive and useless. A link no one is using
4034 * doesn't hurt either.
4035 * @param from Station to check.
4037 void DeleteStaleLinks(Station *from)
4039 for (CargoID c = 0; c < NUM_CARGO; ++c) {
4040 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
4041 GoodsEntry &ge = from->goods[c];
4042 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
4043 if (lg == nullptr) continue;
4044 std::vector<NodeID> to_remove{};
4045 for (Edge &edge : (*lg)[ge.node].edges) {
4046 Station *to = Station::Get((*lg)[edge.dest_node].station);
4047 assert(to->goods[c].node == edge.dest_node);
4048 assert(TimerGameEconomy::date >= edge.LastUpdate());
4049 auto timeout = TimerGameEconomy::Date(LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3));
4050 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4051 bool updated = false;
4053 if (auto_distributed) {
4054 /* Have all vehicles refresh their next hops before deciding to
4055 * remove the node. */
4056 std::vector<Vehicle *> vehicles;
4057 for (OrderList *l : OrderList::Iterate()) {
4058 bool found_from = false;
4059 bool found_to = false;
4060 for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
4061 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
4062 if (order->GetDestination() == from->index) {
4063 found_from = true;
4064 if (found_to) break;
4065 } else if (order->GetDestination() == to->index) {
4066 found_to = true;
4067 if (found_from) break;
4070 if (!found_to || !found_from) continue;
4071 vehicles.push_back(l->GetFirstSharedVehicle());
4074 auto iter = vehicles.begin();
4075 while (iter != vehicles.end()) {
4076 Vehicle *v = *iter;
4077 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4078 if (!v->IsStoppedInDepot() || TimerGameEconomy::date - v->date_of_last_service <= LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
4079 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4081 if (edge.LastUpdate() == TimerGameEconomy::date) {
4082 updated = true;
4083 break;
4086 Vehicle *next_shared = v->NextShared();
4087 if (next_shared) {
4088 *iter = next_shared;
4089 ++iter;
4090 } else {
4091 iter = vehicles.erase(iter);
4094 if (iter == vehicles.end()) iter = vehicles.begin();
4098 if (!updated) {
4099 /* If it's still considered dead remove it. */
4100 to_remove.emplace_back(to->goods[c].node);
4101 ge.flows.DeleteFlows(to->index);
4102 RerouteCargo(from, c, to->index, from->index);
4104 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4105 edge.Restrict();
4106 ge.flows.RestrictFlows(to->index);
4107 RerouteCargo(from, c, to->index, from->index);
4108 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4109 edge.Release();
4112 /* Remove dead edges. */
4113 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4115 assert(TimerGameEconomy::date >= lg->LastCompression());
4116 if (TimerGameEconomy::date - lg->LastCompression() > LinkGraph::COMPRESSION_INTERVAL) {
4117 lg->Compress();
4123 * Increase capacity for a link stat given by station cargo and next hop.
4124 * @param st Station to get the link stats from.
4125 * @param cargo Cargo to increase stat for.
4126 * @param next_station_id Station the consist will be travelling to next.
4127 * @param capacity Capacity to add to link stat.
4128 * @param usage Usage to add to link stat.
4129 * @param mode Update mode to be applied.
4131 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateMode mode)
4133 GoodsEntry &ge1 = st->goods[cargo];
4134 Station *st2 = Station::Get(next_station_id);
4135 GoodsEntry &ge2 = st2->goods[cargo];
4136 LinkGraph *lg = nullptr;
4137 if (ge1.link_graph == INVALID_LINK_GRAPH) {
4138 if (ge2.link_graph == INVALID_LINK_GRAPH) {
4139 if (LinkGraph::CanAllocateItem()) {
4140 lg = new LinkGraph(cargo);
4141 LinkGraphSchedule::instance.Queue(lg);
4142 ge2.link_graph = lg->index;
4143 ge2.node = lg->AddNode(st2);
4144 } else {
4145 Debug(misc, 0, "Can't allocate link graph");
4147 } else {
4148 lg = LinkGraph::Get(ge2.link_graph);
4150 if (lg) {
4151 ge1.link_graph = lg->index;
4152 ge1.node = lg->AddNode(st);
4154 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
4155 lg = LinkGraph::Get(ge1.link_graph);
4156 ge2.link_graph = lg->index;
4157 ge2.node = lg->AddNode(st2);
4158 } else {
4159 lg = LinkGraph::Get(ge1.link_graph);
4160 if (ge1.link_graph != ge2.link_graph) {
4161 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
4162 if (lg->Size() < lg2->Size()) {
4163 LinkGraphSchedule::instance.Unqueue(lg);
4164 lg2->Merge(lg); // Updates GoodsEntries of lg
4165 lg = lg2;
4166 } else {
4167 LinkGraphSchedule::instance.Unqueue(lg2);
4168 lg->Merge(lg2); // Updates GoodsEntries of lg2
4172 if (lg != nullptr) {
4173 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
4178 * Increase capacity for all link stats associated with vehicles in the given consist.
4179 * @param st Station to get the link stats from.
4180 * @param front First vehicle in the consist.
4181 * @param next_station_id Station the consist will be travelling to next.
4183 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4185 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4186 if (v->refit_cap > 0) {
4187 /* The cargo count can indeed be higher than the refit_cap if
4188 * wagons have been auto-replaced and subsequently auto-
4189 * refitted to a higher capacity. The cargo gets redistributed
4190 * among the wagons in that case.
4191 * As usage is not such an important figure anyway we just
4192 * ignore the additional cargo then.*/
4193 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4194 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
4199 /* called for every station each tick */
4200 static void StationHandleSmallTick(BaseStation *st)
4202 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
4204 uint8_t b = st->delete_ctr + 1;
4205 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4206 st->delete_ctr = b;
4208 if (b == 0) UpdateStationRating(Station::From(st));
4211 void OnTick_Station()
4213 if (_game_mode == GM_EDITOR) return;
4215 for (BaseStation *st : BaseStation::Iterate()) {
4216 StationHandleSmallTick(st);
4218 /* Clean up the link graph about once a week. */
4219 if (Station::IsExpected(st) && (TimerGameTick::counter + st->index) % Ticks::STATION_LINKGRAPH_TICKS == 0) {
4220 DeleteStaleLinks(Station::From(st));
4223 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4224 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4225 /* Stop processing this station if it was deleted */
4226 if (!StationHandleBigTick(st)) continue;
4229 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4230 if ((TimerGameTick::counter + st->index) % Ticks::STATION_ACCEPTANCE_TICKS == 0) {
4231 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
4232 TriggerRoadStopAnimation(st, st->xy, SAT_250_TICKS);
4233 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
4238 /** Economy monthly loop for stations. */
4239 static IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::STATION}, [](auto)
4241 for (Station *st : Station::Iterate()) {
4242 for (GoodsEntry &ge : st->goods) {
4243 SB(ge.status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge.status, GoodsEntry::GES_CURRENT_MONTH, 1));
4244 ClrBit(ge.status, GoodsEntry::GES_CURRENT_MONTH);
4249 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4251 ForAllStationsRadius(tile, radius, [&](Station *st) {
4252 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4253 for (GoodsEntry &ge : st->goods) {
4254 if (ge.status != 0) {
4255 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4262 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
4264 /* We can't allocate a CargoPacket? Then don't do anything
4265 * at all; i.e. just discard the incoming cargo. */
4266 if (!CargoPacket::CanAllocateItem()) return 0;
4268 GoodsEntry &ge = st->goods[type];
4269 amount += ge.amount_fract;
4270 ge.amount_fract = GB(amount, 0, 8);
4272 amount >>= 8;
4273 /* No new "real" cargo item yet. */
4274 if (amount == 0) return 0;
4276 StationID next = ge.GetVia(st->index);
4277 ge.cargo.Append(new CargoPacket(st->index, amount, source_type, source_id), next);
4278 LinkGraph *lg = nullptr;
4279 if (ge.link_graph == INVALID_LINK_GRAPH) {
4280 if (LinkGraph::CanAllocateItem()) {
4281 lg = new LinkGraph(type);
4282 LinkGraphSchedule::instance.Queue(lg);
4283 ge.link_graph = lg->index;
4284 ge.node = lg->AddNode(st);
4285 } else {
4286 Debug(misc, 0, "Can't allocate link graph");
4288 } else {
4289 lg = LinkGraph::Get(ge.link_graph);
4291 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4293 if (!ge.HasRating()) {
4294 InvalidateWindowData(WC_STATION_LIST, st->owner);
4295 SetBit(ge.status, GoodsEntry::GES_RATING);
4298 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
4299 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
4300 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
4301 TriggerRoadStopRandomisation(st, st->xy, RSRT_NEW_CARGO, type);
4302 TriggerRoadStopAnimation(st, st->xy, SAT_NEW_CARGO, type);
4305 SetWindowDirty(WC_STATION_VIEW, st->index);
4306 st->MarkTilesDirty(true);
4307 return amount;
4310 static bool IsUniqueStationName(const std::string &name)
4312 for (const Station *st : Station::Iterate()) {
4313 if (!st->name.empty() && st->name == name) return false;
4316 return true;
4320 * Rename a station
4321 * @param flags operation to perform
4322 * @param station_id station ID that is to be renamed
4323 * @param text the new name or an empty string when resetting to the default
4324 * @return the cost of this operation or an error
4326 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
4328 Station *st = Station::GetIfValid(station_id);
4329 if (st == nullptr) return CMD_ERROR;
4331 CommandCost ret = CheckOwnership(st->owner);
4332 if (ret.Failed()) return ret;
4334 bool reset = text.empty();
4336 if (!reset) {
4337 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
4338 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
4341 if (flags & DC_EXEC) {
4342 st->cached_name.clear();
4343 if (reset) {
4344 st->name.clear();
4345 } else {
4346 st->name = text;
4349 st->UpdateVirtCoord();
4350 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
4353 return CommandCost();
4356 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
4358 for (Station *st : nearby) {
4359 if (st->TileIsInCatchment(tile)) stations->insert(st);
4364 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4365 * @return pointer to a StationList containing all stations found
4367 const StationList *StationFinder::GetStations()
4369 if (this->tile != INVALID_TILE) {
4370 if (IsTileType(this->tile, MP_HOUSE)) {
4371 /* Town nearby stations need to be filtered per tile. */
4372 assert(this->w == 1 && this->h == 1);
4373 AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
4374 } else {
4375 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4376 this->stations.insert(st);
4377 return true;
4380 this->tile = INVALID_TILE;
4382 return &this->stations;
4386 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
4388 /* Is the station reserved exclusively for somebody else? */
4389 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4391 /* Lowest possible rating, better not to give cargo anymore. */
4392 if (st->goods[type].rating == 0) return false;
4394 /* Selectively servicing stations, and not this one. */
4395 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
4397 if (IsCargoInClass(type, CC_PASSENGERS)) {
4398 /* Passengers are never served by just a truck stop. */
4399 if (st->facilities == FACIL_TRUCK_STOP) return false;
4400 } else {
4401 /* Non-passengers are never served by just a bus stop. */
4402 if (st->facilities == FACIL_BUS_STOP) return false;
4404 return true;
4407 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
4409 /* Return if nothing to do. Also the rounding below fails for 0. */
4410 if (all_stations->empty()) return 0;
4411 if (amount == 0) return 0;
4413 Station *first_station = nullptr;
4414 typedef std::pair<Station *, uint> StationInfo;
4415 std::vector<StationInfo> used_stations;
4417 for (Station *st : *all_stations) {
4418 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4419 if (!CanMoveGoodsToStation(st, type)) continue;
4421 /* Avoid allocating a vector if there is only one station to significantly
4422 * improve performance in this common case. */
4423 if (first_station == nullptr) {
4424 first_station = st;
4425 continue;
4427 if (used_stations.empty()) {
4428 used_stations.reserve(2);
4429 used_stations.emplace_back(first_station, 0);
4431 used_stations.emplace_back(st, 0);
4434 /* no stations around at all? */
4435 if (first_station == nullptr) return 0;
4437 if (used_stations.empty()) {
4438 /* only one station around */
4439 amount *= first_station->goods[type].rating + 1;
4440 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4443 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4444 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4445 uint best_rating = 0;
4446 uint best_sum = 0; // sum of best ratings for each company
4448 for (auto &p : used_stations) {
4449 auto owner = p.first->owner;
4450 auto rating = p.first->goods[type].rating;
4451 if (rating > company_best[owner]) {
4452 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4453 company_best[owner] = rating;
4454 if (rating > best_rating) best_rating = rating;
4456 company_sum[owner] += rating;
4459 /* From now we'll calculate with fractional cargo amounts.
4460 * First determine how much cargo we really have. */
4461 amount *= best_rating + 1;
4463 uint moving = 0;
4464 for (auto &p : used_stations) {
4465 uint owner = p.first->owner;
4466 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4467 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4468 p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4469 moving += p.second;
4472 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4473 if (amount > moving) {
4474 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4475 return b.first->goods[type].rating < a.first->goods[type].rating;
4478 assert(amount - moving <= used_stations.size());
4479 for (uint i = 0; i < amount - moving; i++) {
4480 used_stations[i].second++;
4484 uint moved = 0;
4485 for (auto &p : used_stations) {
4486 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4489 return moved;
4492 void UpdateStationDockingTiles(Station *st)
4494 st->docking_station.Clear();
4496 /* For neutral stations, start with the industry area instead of dock area */
4497 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4499 if (area->tile == INVALID_TILE) return;
4501 int x = TileX(area->tile);
4502 int y = TileY(area->tile);
4504 /* Expand the area by a tile on each side while
4505 * making sure that we remain inside the map. */
4506 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4507 int x1 = std::max<int>(x - 1, 0);
4509 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4510 int y1 = std::max<int>(y - 1, 0);
4512 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4513 for (TileIndex tile : ta) {
4514 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4518 void BuildOilRig(TileIndex tile)
4520 if (!Station::CanAllocateItem()) {
4521 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4522 return;
4525 Station *st = new Station(tile);
4526 _station_kdtree.Insert(st->index);
4527 st->town = ClosestTownFromTile(tile, UINT_MAX);
4529 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4531 assert(IsTileType(tile, MP_INDUSTRY));
4532 /* Mark industry as associated both ways */
4533 st->industry = Industry::GetByTile(tile);
4534 st->industry->neutral_station = st;
4535 DeleteAnimatedTile(tile);
4536 MakeOilrig(tile, st->index, GetWaterClass(tile));
4538 st->owner = OWNER_NONE;
4539 st->airport.type = AT_OILRIG;
4540 st->airport.Add(tile);
4541 st->ship_station.Add(tile);
4542 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4543 st->build_date = TimerGameCalendar::date;
4544 UpdateStationDockingTiles(st);
4546 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4548 st->UpdateVirtCoord();
4550 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4551 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4552 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4553 if (_settings_game.station.serve_neutral_industries) {
4554 StationList nearby = std::move(st->industry->stations_near);
4555 st->industry->stations_near.clear();
4556 for (Station *near : nearby) {
4557 near->RecomputeCatchment(true);
4558 UpdateStationAcceptance(near, true);
4562 st->RecomputeCatchment();
4563 UpdateStationAcceptance(st, false);
4566 void DeleteOilRig(TileIndex tile)
4568 Station *st = Station::GetByTile(tile);
4570 MakeWaterKeepingClass(tile, OWNER_NONE);
4572 /* The oil rig station is not supposed to be shared with anything else */
4573 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4574 if (st->industry != nullptr && st->industry->neutral_station == st) {
4575 /* Don't leave dangling neutral station pointer */
4576 st->industry->neutral_station = nullptr;
4578 delete st;
4581 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4583 if (IsAnyRoadStopTile(tile)) {
4584 for (RoadTramType rtt : _roadtramtypes) {
4585 /* Update all roadtypes, no matter if they are present */
4586 if (GetRoadOwner(tile, rtt) == old_owner) {
4587 RoadType rt = GetRoadType(tile, rtt);
4588 if (rt != INVALID_ROADTYPE) {
4589 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4590 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4591 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4593 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4598 if (!IsTileOwner(tile, old_owner)) return;
4600 if (new_owner != INVALID_OWNER) {
4601 /* Update company infrastructure counts. Only do it here
4602 * if the new owner is valid as otherwise the clear
4603 * command will do it for us. No need to dirty windows
4604 * here, we'll redraw the whole screen anyway.*/
4605 Company *old_company = Company::Get(old_owner);
4606 Company *new_company = Company::Get(new_owner);
4608 /* Update counts for underlying infrastructure. */
4609 switch (GetStationType(tile)) {
4610 case STATION_RAIL:
4611 case STATION_WAYPOINT:
4612 if (!IsStationTileBlocked(tile)) {
4613 old_company->infrastructure.rail[GetRailType(tile)]--;
4614 new_company->infrastructure.rail[GetRailType(tile)]++;
4616 break;
4618 case STATION_BUS:
4619 case STATION_TRUCK:
4620 case STATION_ROADWAYPOINT:
4621 /* Road stops were already handled above. */
4622 break;
4624 case STATION_BUOY:
4625 case STATION_DOCK:
4626 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4627 old_company->infrastructure.water--;
4628 new_company->infrastructure.water++;
4630 break;
4632 default:
4633 break;
4636 /* Update station tile count. */
4637 if (!IsBuoy(tile) && !IsAirport(tile)) {
4638 old_company->infrastructure.station--;
4639 new_company->infrastructure.station++;
4642 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4643 SetTileOwner(tile, new_owner);
4644 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4645 } else {
4646 if (IsDriveThroughStopTile(tile)) {
4647 /* Remove the drive-through road stop */
4648 if (IsRoadWaypoint(tile)) {
4649 Command<CMD_REMOVE_FROM_ROAD_WAYPOINT>::Do(DC_EXEC | DC_BANKRUPT, tile, tile);
4650 } else {
4651 Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4653 assert(IsTileType(tile, MP_ROAD));
4654 /* Change owner of tile and all roadtypes */
4655 ChangeTileOwner(tile, old_owner, new_owner);
4656 } else {
4657 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
4658 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4659 * Update owner of buoy if it was not removed (was in orders).
4660 * Do not update when owned by OWNER_WATER (sea and rivers). */
4661 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4667 * Check if a drive-through road stop tile can be cleared.
4668 * Road stops built on town-owned roads check the conditions
4669 * that would allow clearing of the original road.
4670 * @param tile The road stop tile to check.
4671 * @param flags Command flags.
4672 * @return A succeeded command if the road can be removed, a failed command with the relevant error message otherwise.
4674 static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4676 /* Water flooding can always clear road stops. */
4677 if (_current_company == OWNER_WATER) return CommandCost();
4679 CommandCost ret;
4681 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4682 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4683 if (tram_owner != OWNER_NONE) {
4684 ret = CheckOwnership(tram_owner);
4685 if (ret.Failed()) return ret;
4689 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4690 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4691 if (road_owner == OWNER_TOWN) {
4692 ret = CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags);
4693 if (ret.Failed()) return ret;
4694 } else if (road_owner != OWNER_NONE) {
4695 ret = CheckOwnership(road_owner);
4696 if (ret.Failed()) return ret;
4700 return CommandCost();
4704 * Clear a single tile of a station.
4705 * @param tile The tile to clear.
4706 * @param flags The DoCommand flags related to the "command".
4707 * @return The cost, or error of clearing.
4709 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4711 if (flags & DC_AUTO) {
4712 switch (GetStationType(tile)) {
4713 default: break;
4714 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4715 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4716 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4717 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);
4718 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);
4719 case STATION_ROADWAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4720 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4721 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4722 case STATION_OILRIG:
4723 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4724 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4728 switch (GetStationType(tile)) {
4729 case STATION_RAIL: return RemoveRailStation(tile, flags);
4730 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4731 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4732 case STATION_TRUCK: [[fallthrough]];
4733 case STATION_BUS:
4734 if (IsDriveThroughStopTile(tile)) {
4735 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4736 if (remove_road.Failed()) return remove_road;
4738 return RemoveRoadStop(tile, flags);
4739 case STATION_ROADWAYPOINT: {
4740 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4741 if (remove_road.Failed()) return remove_road;
4742 return RemoveRoadWaypointStop(tile, flags);
4744 case STATION_BUOY: return RemoveBuoy(tile, flags);
4745 case STATION_DOCK: return RemoveDock(tile, flags);
4746 default: break;
4749 return CMD_ERROR;
4752 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4754 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4755 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4756 * TTDP does not call it.
4758 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4759 switch (GetStationType(tile)) {
4760 case STATION_WAYPOINT:
4761 case STATION_RAIL: {
4762 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4763 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4764 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4765 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4768 case STATION_AIRPORT:
4769 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4771 case STATION_TRUCK:
4772 case STATION_BUS: {
4773 DiagDirection direction = GetRoadStopDir(tile);
4774 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4775 if (IsDriveThroughStopTile(tile)) {
4776 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4778 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4781 default: break;
4785 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4789 * Get flow for a station.
4790 * @param st Station to get flow for.
4791 * @return Flow for st.
4793 uint FlowStat::GetShare(StationID st) const
4795 uint32_t prev = 0;
4796 for (const auto &it : this->shares) {
4797 if (it.second == st) {
4798 return it.first - prev;
4799 } else {
4800 prev = it.first;
4803 return 0;
4807 * Get a station a package can be routed to, but exclude the given ones.
4808 * @param excluded StationID not to be selected.
4809 * @param excluded2 Another StationID not to be selected.
4810 * @return A station ID from the shares map.
4812 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4814 if (this->unrestricted == 0) return INVALID_STATION;
4815 assert(!this->shares.empty());
4816 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4817 assert(it != this->shares.end() && it->first <= this->unrestricted);
4818 if (it->second != excluded && it->second != excluded2) return it->second;
4820 /* We've hit one of the excluded stations.
4821 * Draw another share, from outside its range. */
4823 uint end = it->first;
4824 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4825 uint interval = end - begin;
4826 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4827 uint new_max = this->unrestricted - interval;
4828 uint rand = RandomRange(new_max);
4829 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4830 this->shares.upper_bound(rand + interval);
4831 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4832 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4834 /* We've hit the second excluded station.
4835 * Same as before, only a bit more complicated. */
4837 uint end2 = it2->first;
4838 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4839 uint interval2 = end2 - begin2;
4840 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4841 new_max -= interval2;
4842 if (begin > begin2) {
4843 Swap(begin, begin2);
4844 Swap(end, end2);
4845 Swap(interval, interval2);
4847 rand = RandomRange(new_max);
4848 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4849 if (rand < begin) {
4850 it3 = this->shares.upper_bound(rand);
4851 } else if (rand < begin2 - interval) {
4852 it3 = this->shares.upper_bound(rand + interval);
4853 } else {
4854 it3 = this->shares.upper_bound(rand + interval + interval2);
4856 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4857 return it3->second;
4861 * Reduce all flows to minimum capacity so that they don't get in the way of
4862 * link usage statistics too much. Keep them around, though, to continue
4863 * routing any remaining cargo.
4865 void FlowStat::Invalidate()
4867 assert(!this->shares.empty());
4868 SharesMap new_shares;
4869 uint i = 0;
4870 for (const auto &it : this->shares) {
4871 new_shares[++i] = it.second;
4872 if (it.first == this->unrestricted) this->unrestricted = i;
4874 this->shares.swap(new_shares);
4875 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4879 * Change share for specified station. By specifying INT_MIN as parameter you
4880 * can erase a share. Newly added flows will be unrestricted.
4881 * @param st Next Hop to be removed.
4882 * @param flow Share to be added or removed.
4884 void FlowStat::ChangeShare(StationID st, int flow)
4886 /* We assert only before changing as afterwards the shares can actually
4887 * be empty. In that case the whole flow stat must be deleted then. */
4888 assert(!this->shares.empty());
4890 uint removed_shares = 0;
4891 uint added_shares = 0;
4892 uint last_share = 0;
4893 SharesMap new_shares;
4894 for (const auto &it : this->shares) {
4895 if (it.second == st) {
4896 if (flow < 0) {
4897 uint share = it.first - last_share;
4898 if (flow == INT_MIN || (uint)(-flow) >= share) {
4899 removed_shares += share;
4900 if (it.first <= this->unrestricted) this->unrestricted -= share;
4901 if (flow != INT_MIN) flow += share;
4902 last_share = it.first;
4903 continue; // remove the whole share
4905 removed_shares += (uint)(-flow);
4906 } else {
4907 added_shares += (uint)(flow);
4909 if (it.first <= this->unrestricted) this->unrestricted += flow;
4911 /* If we don't continue above the whole flow has been added or
4912 * removed. */
4913 flow = 0;
4915 new_shares[it.first + added_shares - removed_shares] = it.second;
4916 last_share = it.first;
4918 if (flow > 0) {
4919 new_shares[last_share + (uint)flow] = st;
4920 if (this->unrestricted < last_share) {
4921 this->ReleaseShare(st);
4922 } else {
4923 this->unrestricted += flow;
4926 this->shares.swap(new_shares);
4930 * Restrict a flow by moving it to the end of the map and decreasing the amount
4931 * of unrestricted flow.
4932 * @param st Station of flow to be restricted.
4934 void FlowStat::RestrictShare(StationID st)
4936 assert(!this->shares.empty());
4937 uint flow = 0;
4938 uint last_share = 0;
4939 SharesMap new_shares;
4940 for (auto &it : this->shares) {
4941 if (flow == 0) {
4942 if (it.first > this->unrestricted) return; // Not present or already restricted.
4943 if (it.second == st) {
4944 flow = it.first - last_share;
4945 this->unrestricted -= flow;
4946 } else {
4947 new_shares[it.first] = it.second;
4949 } else {
4950 new_shares[it.first - flow] = it.second;
4952 last_share = it.first;
4954 if (flow == 0) return;
4955 new_shares[last_share + flow] = st;
4956 this->shares.swap(new_shares);
4957 assert(!this->shares.empty());
4961 * Release ("unrestrict") a flow by moving it to the begin of the map and
4962 * increasing the amount of unrestricted flow.
4963 * @param st Station of flow to be released.
4965 void FlowStat::ReleaseShare(StationID st)
4967 assert(!this->shares.empty());
4968 uint flow = 0;
4969 uint next_share = 0;
4970 bool found = false;
4971 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4972 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4973 if (found) {
4974 flow = next_share - it->first;
4975 this->unrestricted += flow;
4976 break;
4977 } else {
4978 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4979 if (it->second == st) found = true;
4981 next_share = it->first;
4983 if (flow == 0) return;
4984 SharesMap new_shares;
4985 new_shares[flow] = st;
4986 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4987 if (it->second != st) {
4988 new_shares[flow + it->first] = it->second;
4989 } else {
4990 flow = 0;
4993 this->shares.swap(new_shares);
4994 assert(!this->shares.empty());
4998 * Scale all shares from link graph's runtime to monthly values.
4999 * @param runtime Time the link graph has been running without compression.
5000 * @pre runtime must be greater than 0 as we don't want infinite flow values.
5002 void FlowStat::ScaleToMonthly(uint runtime)
5004 assert(runtime > 0);
5005 SharesMap new_shares;
5006 uint share = 0;
5007 for (auto i : this->shares) {
5008 share = std::max(share + 1, i.first * 30 / runtime);
5009 new_shares[share] = i.second;
5010 if (this->unrestricted == i.first) this->unrestricted = share;
5012 this->shares.swap(new_shares);
5016 * Add some flow from "origin", going via "via".
5017 * @param origin Origin of the flow.
5018 * @param via Next hop.
5019 * @param flow Amount of flow to be added.
5021 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5023 FlowStatMap::iterator origin_it = this->find(origin);
5024 if (origin_it == this->end()) {
5025 this->emplace(origin, FlowStat(via, flow));
5026 } else {
5027 origin_it->second.ChangeShare(via, flow);
5028 assert(!origin_it->second.GetShares()->empty());
5033 * Pass on some flow, remembering it as invalid, for later subtraction from
5034 * locally consumed flow. This is necessary because we can't have negative
5035 * flows and we don't want to sort the flows before adding them up.
5036 * @param origin Origin of the flow.
5037 * @param via Next hop.
5038 * @param flow Amount of flow to be passed.
5040 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5042 FlowStatMap::iterator prev_it = this->find(origin);
5043 if (prev_it == this->end()) {
5044 FlowStat fs(via, flow);
5045 fs.AppendShare(INVALID_STATION, flow);
5046 this->emplace(origin, fs);
5047 } else {
5048 prev_it->second.ChangeShare(via, flow);
5049 prev_it->second.ChangeShare(INVALID_STATION, flow);
5050 assert(!prev_it->second.GetShares()->empty());
5055 * Subtract invalid flows from locally consumed flow.
5056 * @param self ID of own station.
5058 void FlowStatMap::FinalizeLocalConsumption(StationID self)
5060 for (auto &i : *this) {
5061 FlowStat &fs = i.second;
5062 uint local = fs.GetShare(INVALID_STATION);
5063 if (local > INT_MAX) { // make sure it fits in an int
5064 fs.ChangeShare(self, -INT_MAX);
5065 fs.ChangeShare(INVALID_STATION, -INT_MAX);
5066 local -= INT_MAX;
5068 fs.ChangeShare(self, -(int)local);
5069 fs.ChangeShare(INVALID_STATION, -(int)local);
5071 /* If the local share is used up there must be a share for some
5072 * remote station. */
5073 assert(!fs.GetShares()->empty());
5078 * Delete all flows at a station for specific cargo and destination.
5079 * @param via Remote station of flows to be deleted.
5080 * @return IDs of source stations for which the complete FlowStat, not only a
5081 * share, has been erased.
5083 StationIDStack FlowStatMap::DeleteFlows(StationID via)
5085 StationIDStack ret;
5086 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5087 FlowStat &s_flows = f_it->second;
5088 s_flows.ChangeShare(via, INT_MIN);
5089 if (s_flows.GetShares()->empty()) {
5090 ret.Push(f_it->first);
5091 this->erase(f_it++);
5092 } else {
5093 ++f_it;
5096 return ret;
5100 * Restrict all flows at a station for specific cargo and destination.
5101 * @param via Remote station of flows to be restricted.
5103 void FlowStatMap::RestrictFlows(StationID via)
5105 for (auto &it : *this) {
5106 it.second.RestrictShare(via);
5111 * Release all flows at a station for specific cargo and destination.
5112 * @param via Remote station of flows to be released.
5114 void FlowStatMap::ReleaseFlows(StationID via)
5116 for (auto &it : *this) {
5117 it.second.ReleaseShare(via);
5122 * Get the sum of all flows from this FlowStatMap.
5123 * @return sum of all flows.
5125 uint FlowStatMap::GetFlow() const
5127 uint ret = 0;
5128 for (const auto &it : *this) {
5129 ret += (--(it.second.GetShares()->end()))->first;
5131 return ret;
5135 * Get the sum of flows via a specific station from this FlowStatMap.
5136 * @param via Remote station to look for.
5137 * @return all flows for 'via' added up.
5139 uint FlowStatMap::GetFlowVia(StationID via) const
5141 uint ret = 0;
5142 for (const auto &it : *this) {
5143 ret += it.second.GetShare(via);
5145 return ret;
5149 * Get the sum of flows from a specific station from this FlowStatMap.
5150 * @param from Origin station to look for.
5151 * @return all flows from 'from' added up.
5153 uint FlowStatMap::GetFlowFrom(StationID from) const
5155 FlowStatMap::const_iterator i = this->find(from);
5156 if (i == this->end()) return 0;
5157 return (--(i->second.GetShares()->end()))->first;
5161 * Get the flow from a specific station via a specific other station.
5162 * @param from Origin station to look for.
5163 * @param via Remote station to look for.
5164 * @return flow share originating at 'from' and going to 'via'.
5166 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5168 FlowStatMap::const_iterator i = this->find(from);
5169 if (i == this->end()) return 0;
5170 return i->second.GetShare(via);
5173 extern const TileTypeProcs _tile_type_station_procs = {
5174 DrawTile_Station, // draw_tile_proc
5175 GetSlopePixelZ_Station, // get_slope_z_proc
5176 ClearTile_Station, // clear_tile_proc
5177 nullptr, // add_accepted_cargo_proc
5178 GetTileDesc_Station, // get_tile_desc_proc
5179 GetTileTrackStatus_Station, // get_tile_track_status_proc
5180 ClickTile_Station, // click_tile_proc
5181 AnimateTile_Station, // animate_tile_proc
5182 TileLoop_Station, // tile_loop_proc
5183 ChangeTileOwner_Station, // change_tile_owner_proc
5184 nullptr, // add_produced_cargo_proc
5185 VehicleEnter_Station, // vehicle_enter_tile_proc
5186 GetFoundation_Station, // get_foundation_proc
5187 TerraformTile_Station, // terraform_tile_proc