Fix: CmdSetAutoReplace didn't validate group type and engine type match (#9950)
[openttd-github.git] / src / station_cmd.cpp
blobf0bde9f45fdb7e25e49ba706e235d307a7df99fa
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file station_cmd.cpp Handling of station tiles. */
10 #include "stdafx.h"
11 #include "aircraft.h"
12 #include "bridge_map.h"
13 #include "viewport_func.h"
14 #include "viewport_kdtree.h"
15 #include "command_func.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "train.h"
19 #include "ship.h"
20 #include "roadveh.h"
21 #include "industry.h"
22 #include "newgrf_cargo.h"
23 #include "newgrf_debug.h"
24 #include "newgrf_station.h"
25 #include "newgrf_canal.h" /* For the buoy */
26 #include "pathfinder/yapf/yapf_cache.h"
27 #include "road_internal.h" /* For drawing catenary/checking road removal */
28 #include "autoslope.h"
29 #include "water.h"
30 #include "strings_func.h"
31 #include "clear_func.h"
32 #include "date_func.h"
33 #include "vehicle_func.h"
34 #include "string_func.h"
35 #include "animated_tile_func.h"
36 #include "elrail_func.h"
37 #include "station_base.h"
38 #include "station_func.h"
39 #include "station_kdtree.h"
40 #include "roadstop_base.h"
41 #include "newgrf_railtype.h"
42 #include "newgrf_roadtype.h"
43 #include "waypoint_base.h"
44 #include "waypoint_func.h"
45 #include "pbs.h"
46 #include "debug.h"
47 #include "core/random_func.hpp"
48 #include "company_base.h"
49 #include "table/airporttile_ids.h"
50 #include "newgrf_airporttiles.h"
51 #include "order_backup.h"
52 #include "newgrf_house.h"
53 #include "company_gui.h"
54 #include "linkgraph/linkgraph_base.h"
55 #include "linkgraph/refresh.h"
56 #include "widgets/station_widget.h"
57 #include "tunnelbridge_map.h"
58 #include "station_cmd.h"
59 #include "waypoint_cmd.h"
60 #include "landscape_cmd.h"
61 #include "rail_cmd.h"
63 #include "table/strings.h"
65 #include "safeguards.h"
67 /**
68 * Static instance of FlowStat::SharesMap.
69 * Note: This instance is created on task start.
70 * Lazy creation on first usage results in a data race between the CDist threads.
72 /* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
74 /**
75 * Check whether the given tile is a hangar.
76 * @param t the tile to of whether it is a hangar.
77 * @pre IsTileType(t, MP_STATION)
78 * @return true if and only if the tile is a hangar.
80 bool IsHangar(TileIndex t)
82 assert(IsTileType(t, MP_STATION));
84 /* If the tile isn't an airport there's no chance it's a hangar. */
85 if (!IsAirport(t)) return false;
87 const Station *st = Station::GetByTile(t);
88 const AirportSpec *as = st->airport.GetSpec();
90 for (uint i = 0; i < as->nof_depots; i++) {
91 if (st->airport.GetHangarTile(i) == t) return true;
94 return false;
97 /**
98 * Look for a station owned by the given company around the given tile area.
99 * @param ta the area to search over
100 * @param closest_station the closest owned station found so far
101 * @param company the company whose stations to look for
102 * @param st to 'return' the found station
103 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
105 template <class T>
106 CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st)
108 ta.Expand(1);
110 /* check around to see if there are any stations there owned by the company */
111 for (TileIndex tile_cur : ta) {
112 if (IsTileType(tile_cur, MP_STATION)) {
113 StationID t = GetStationIndex(tile_cur);
114 if (!T::IsValidID(t) || Station::Get(t)->owner != company) continue;
115 if (closest_station == INVALID_STATION) {
116 closest_station = t;
117 } else if (closest_station != t) {
118 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
122 *st = (closest_station == INVALID_STATION) ? nullptr : T::Get(closest_station);
123 return CommandCost();
127 * Function to check whether the given tile matches some criterion.
128 * @param tile the tile to check
129 * @return true if it matches, false otherwise
131 typedef bool (*CMSAMatcher)(TileIndex tile);
134 * Counts the numbers of tiles matching a specific type in the area around
135 * @param tile the center tile of the 'count area'
136 * @param cmp the comparator/matcher (@see CMSAMatcher)
137 * @return the number of matching tiles around
139 static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
141 int num = 0;
143 for (int dx = -3; dx <= 3; dx++) {
144 for (int dy = -3; dy <= 3; dy++) {
145 TileIndex t = TileAddWrap(tile, dx, dy);
146 if (t != INVALID_TILE && cmp(t)) num++;
150 return num;
154 * Check whether the tile is a mine.
155 * @param tile the tile to investigate.
156 * @return true if and only if the tile is a mine
158 static bool CMSAMine(TileIndex tile)
160 /* No industry */
161 if (!IsTileType(tile, MP_INDUSTRY)) return false;
163 const Industry *ind = Industry::GetByTile(tile);
165 /* No extractive industry */
166 if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_EXTRACTIVE) == 0) return false;
168 for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
169 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
170 * Also the production of passengers and mail is ignored. */
171 if (ind->produced_cargo[i] != CT_INVALID &&
172 (CargoSpec::Get(ind->produced_cargo[i])->classes & (CC_LIQUID | CC_PASSENGERS | CC_MAIL)) == 0) {
173 return true;
177 return false;
181 * Check whether the tile is water.
182 * @param tile the tile to investigate.
183 * @return true if and only if the tile is a water tile
185 static bool CMSAWater(TileIndex tile)
187 return IsTileType(tile, MP_WATER) && IsWater(tile);
191 * Check whether the tile is a tree.
192 * @param tile the tile to investigate.
193 * @return true if and only if the tile is a tree tile
195 static bool CMSATree(TileIndex tile)
197 return IsTileType(tile, MP_TREES);
200 #define M(x) ((x) - STR_SV_STNAME)
202 enum StationNaming {
203 STATIONNAMING_RAIL,
204 STATIONNAMING_ROAD,
205 STATIONNAMING_AIRPORT,
206 STATIONNAMING_OILRIG,
207 STATIONNAMING_DOCK,
208 STATIONNAMING_HELIPORT,
211 /** Information to handle station action 0 property 24 correctly */
212 struct StationNameInformation {
213 uint32 free_names; ///< Current bitset of free names (we can remove names).
214 bool *indtypes; ///< Array of bools telling whether an industry type has been found.
218 * Find a station action 0 property 24 station name, or reduce the
219 * free_names if needed.
220 * @param tile the tile to search
221 * @param user_data the StationNameInformation to base the search on
222 * @return true if the tile contains an industry that has not given
223 * its name to one of the other stations in town.
225 static bool FindNearIndustryName(TileIndex tile, void *user_data)
227 /* All already found industry types */
228 StationNameInformation *sni = (StationNameInformation*)user_data;
229 if (!IsTileType(tile, MP_INDUSTRY)) return false;
231 /* If the station name is undefined it means that it doesn't name a station */
232 IndustryType indtype = GetIndustryType(tile);
233 if (GetIndustrySpec(indtype)->station_name == STR_UNDEFINED) return false;
235 /* In all cases if an industry that provides a name is found two of
236 * the standard names will be disabled. */
237 sni->free_names &= ~(1 << M(STR_SV_STNAME_OILFIELD) | 1 << M(STR_SV_STNAME_MINES));
238 return !sni->indtypes[indtype];
241 static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
243 static const uint32 _gen_station_name_bits[] = {
244 0, // STATIONNAMING_RAIL
245 0, // STATIONNAMING_ROAD
246 1U << M(STR_SV_STNAME_AIRPORT), // STATIONNAMING_AIRPORT
247 1U << M(STR_SV_STNAME_OILFIELD), // STATIONNAMING_OILRIG
248 1U << M(STR_SV_STNAME_DOCKS), // STATIONNAMING_DOCK
249 1U << M(STR_SV_STNAME_HELIPORT), // STATIONNAMING_HELIPORT
252 const Town *t = st->town;
253 uint32 free_names = UINT32_MAX;
255 bool indtypes[NUM_INDUSTRYTYPES];
256 memset(indtypes, 0, sizeof(indtypes));
258 for (const Station *s : Station::Iterate()) {
259 if (s != st && s->town == t) {
260 if (s->indtype != IT_INVALID) {
261 indtypes[s->indtype] = true;
262 StringID name = GetIndustrySpec(s->indtype)->station_name;
263 if (name != STR_UNDEFINED) {
264 /* Filter for other industrytypes with the same name */
265 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
266 const IndustrySpec *indsp = GetIndustrySpec(it);
267 if (indsp->enabled && indsp->station_name == name) indtypes[it] = true;
270 continue;
272 uint str = M(s->string_id);
273 if (str <= 0x20) {
274 if (str == M(STR_SV_STNAME_FOREST)) {
275 str = M(STR_SV_STNAME_WOODS);
277 ClrBit(free_names, str);
282 TileIndex indtile = tile;
283 StationNameInformation sni = { free_names, indtypes };
284 if (CircularTileSearch(&indtile, 7, FindNearIndustryName, &sni)) {
285 /* An industry has been found nearby */
286 IndustryType indtype = GetIndustryType(indtile);
287 const IndustrySpec *indsp = GetIndustrySpec(indtype);
288 /* STR_NULL means it only disables oil rig/mines */
289 if (indsp->station_name != STR_NULL) {
290 st->indtype = indtype;
291 return STR_SV_STNAME_FALLBACK;
295 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
296 free_names = sni.free_names;
298 /* check default names */
299 uint32 tmp = free_names & _gen_station_name_bits[name_class];
300 if (tmp != 0) return STR_SV_STNAME + FindFirstBit(tmp);
302 /* check mine? */
303 if (HasBit(free_names, M(STR_SV_STNAME_MINES))) {
304 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
305 return STR_SV_STNAME_MINES;
309 /* check close enough to town to get central as name? */
310 if (DistanceMax(tile, t->xy) < 8) {
311 if (HasBit(free_names, M(STR_SV_STNAME))) return STR_SV_STNAME;
313 if (HasBit(free_names, M(STR_SV_STNAME_CENTRAL))) return STR_SV_STNAME_CENTRAL;
316 /* Check lakeside */
317 if (HasBit(free_names, M(STR_SV_STNAME_LAKESIDE)) &&
318 DistanceFromEdge(tile) < 20 &&
319 CountMapSquareAround(tile, CMSAWater) >= 5) {
320 return STR_SV_STNAME_LAKESIDE;
323 /* Check woods */
324 if (HasBit(free_names, M(STR_SV_STNAME_WOODS)) && (
325 CountMapSquareAround(tile, CMSATree) >= 8 ||
326 CountMapSquareAround(tile, IsTileForestIndustry) >= 2)
328 return _settings_game.game_creation.landscape == LT_TROPIC ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
331 /* check elevation compared to town */
332 int z = GetTileZ(tile);
333 int z2 = GetTileZ(t->xy);
334 if (z < z2) {
335 if (HasBit(free_names, M(STR_SV_STNAME_VALLEY))) return STR_SV_STNAME_VALLEY;
336 } else if (z > z2) {
337 if (HasBit(free_names, M(STR_SV_STNAME_HEIGHTS))) return STR_SV_STNAME_HEIGHTS;
340 /* check direction compared to town */
341 static const int8 _direction_and_table[] = {
342 ~( (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
343 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
344 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_EAST)) | (1 << M(STR_SV_STNAME_NORTH)) ),
345 ~( (1 << M(STR_SV_STNAME_SOUTH)) | (1 << M(STR_SV_STNAME_WEST)) | (1 << M(STR_SV_STNAME_EAST)) ),
348 free_names &= _direction_and_table[
349 (TileX(tile) < TileX(t->xy)) +
350 (TileY(tile) < TileY(t->xy)) * 2];
352 tmp = free_names & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
353 return (tmp == 0) ? STR_SV_STNAME_FALLBACK : (STR_SV_STNAME + FindFirstBit(tmp));
355 #undef M
358 * Find the closest deleted station of the current company
359 * @param tile the tile to search from.
360 * @return the closest station or nullptr if too far.
362 static Station *GetClosestDeletedStation(TileIndex tile)
364 uint threshold = 8;
366 Station *best_station = nullptr;
367 ForAllStationsRadius(tile, threshold, [&](Station *st) {
368 if (!st->IsInUse() && st->owner == _current_company) {
369 uint cur_dist = DistanceManhattan(tile, st->xy);
371 if (cur_dist < threshold) {
372 threshold = cur_dist;
373 best_station = st;
374 } else if (cur_dist == threshold && best_station != nullptr) {
375 /* In case of a tie, lowest station ID wins */
376 if (st->index < best_station->index) best_station = st;
381 return best_station;
385 void Station::GetTileArea(TileArea *ta, StationType type) const
387 switch (type) {
388 case STATION_RAIL:
389 *ta = this->train_station;
390 return;
392 case STATION_AIRPORT:
393 *ta = this->airport;
394 return;
396 case STATION_TRUCK:
397 *ta = this->truck_station;
398 return;
400 case STATION_BUS:
401 *ta = this->bus_station;
402 return;
404 case STATION_DOCK:
405 case STATION_OILRIG:
406 *ta = this->docking_station;
407 return;
409 default: NOT_REACHED();
414 * Update the virtual coords needed to draw the station sign.
416 void Station::UpdateVirtCoord()
418 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
420 pt.y -= 32 * ZOOM_LVL_BASE;
421 if ((this->facilities & FACIL_AIRPORT) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_LVL_BASE;
423 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
425 SetDParam(0, this->index);
426 SetDParam(1, this->facilities);
427 this->sign.UpdatePosition(pt.x, pt.y, STR_VIEWPORT_STATION);
429 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
431 SetWindowDirty(WC_STATION_VIEW, this->index);
435 * Move the station main coordinate somewhere else.
436 * @param new_xy new tile location of the sign
438 void Station::MoveSign(TileIndex new_xy)
440 if (this->xy == new_xy) return;
442 _station_kdtree.Remove(this->index);
444 this->BaseStation::MoveSign(new_xy);
446 _station_kdtree.Insert(this->index);
449 /** Update the virtual coords needed to draw the station sign for all stations. */
450 void UpdateAllStationVirtCoords()
452 for (BaseStation *st : BaseStation::Iterate()) {
453 st->UpdateVirtCoord();
457 void BaseStation::FillCachedName() const
459 char buf[MAX_LENGTH_STATION_NAME_CHARS * MAX_CHAR_LENGTH];
460 int64 args_array[] = { this->index };
461 StringParameters tmp_params(args_array);
462 char *end = GetStringWithArgs(buf, Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, &tmp_params, lastof(buf));
463 this->cached_name.assign(buf, end);
466 void ClearAllStationCachedNames()
468 for (BaseStation *st : BaseStation::Iterate()) {
469 st->cached_name.clear();
474 * Get a mask of the cargo types that the station accepts.
475 * @param st Station to query
476 * @return the expected mask
478 static CargoTypes GetAcceptanceMask(const Station *st)
480 CargoTypes mask = 0;
482 for (CargoID i = 0; i < NUM_CARGO; i++) {
483 if (HasBit(st->goods[i].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(mask, i);
485 return mask;
489 * Items contains the two cargo names that are to be accepted or rejected.
490 * msg is the string id of the message to display.
492 static void ShowRejectOrAcceptNews(const Station *st, uint num_items, CargoID *cargo, StringID msg)
494 for (uint i = 0; i < num_items; i++) {
495 SetDParam(i + 1, CargoSpec::Get(cargo[i])->name);
498 SetDParam(0, st->index);
499 AddNewsItem(msg, NT_ACCEPTANCE, NF_INCOLOUR | NF_SMALL, NR_STATION, st->index);
503 * Get the cargo types being produced around the tile (in a rectangle).
504 * @param north_tile Northern most tile of area
505 * @param w X extent of the area
506 * @param h Y extent of the area
507 * @param rad Search radius in addition to the given area
509 CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
511 CargoArray produced;
512 std::set<IndustryID> industries;
513 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
515 /* Loop over all tiles to get the produced cargo of
516 * everything except industries */
517 for (TileIndex tile : ta) {
518 if (IsTileType(tile, MP_INDUSTRY)) industries.insert(GetIndustryIndex(tile));
519 AddProducedCargo(tile, produced);
522 /* Loop over the seen industries. They produce cargo for
523 * anything that is within 'rad' of any one of their tiles.
525 for (IndustryID industry : industries) {
526 const Industry *i = Industry::Get(industry);
527 /* Skip industry with neutral station */
528 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
530 for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
531 CargoID cargo = i->produced_cargo[j];
532 if (cargo != CT_INVALID) produced[cargo]++;
536 return produced;
540 * Get the acceptance of cargoes around the tile in 1/8.
541 * @param center_tile Center of the search area
542 * @param w X extent of area
543 * @param h Y extent of area
544 * @param rad Search radius in addition to given area
545 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
546 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
548 CargoArray GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad, CargoTypes *always_accepted)
550 CargoArray acceptance;
551 if (always_accepted != nullptr) *always_accepted = 0;
553 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
555 for (TileIndex tile : ta) {
556 /* Ignore industry if it has a neutral station. */
557 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, MP_INDUSTRY) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
559 AddAcceptedCargo(tile, acceptance, always_accepted);
562 return acceptance;
566 * Get the acceptance of cargoes around the station in.
567 * @param st Station to get acceptance of.
568 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
570 static CargoArray GetAcceptanceAroundStation(const Station *st, CargoTypes *always_accepted)
572 CargoArray acceptance;
573 if (always_accepted != nullptr) *always_accepted = 0;
575 BitmapTileIterator it(st->catchment_tiles);
576 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
577 AddAcceptedCargo(tile, acceptance, always_accepted);
580 return acceptance;
584 * Update the acceptance for a station.
585 * @param st Station to update
586 * @param show_msg controls whether to display a message that acceptance was changed.
588 void UpdateStationAcceptance(Station *st, bool show_msg)
590 /* old accepted goods types */
591 CargoTypes old_acc = GetAcceptanceMask(st);
593 /* And retrieve the acceptance. */
594 CargoArray acceptance;
595 if (!st->rect.IsEmpty()) {
596 acceptance = GetAcceptanceAroundStation(st, &st->always_accepted);
599 /* Adjust in case our station only accepts fewer kinds of goods */
600 for (CargoID i = 0; i < NUM_CARGO; i++) {
601 uint amt = acceptance[i];
603 /* Make sure the station can accept the goods type. */
604 bool is_passengers = IsCargoInClass(i, CC_PASSENGERS);
605 if ((!is_passengers && !(st->facilities & ~FACIL_BUS_STOP)) ||
606 (is_passengers && !(st->facilities & ~FACIL_TRUCK_STOP))) {
607 amt = 0;
610 GoodsEntry &ge = st->goods[i];
611 SB(ge.status, GoodsEntry::GES_ACCEPTANCE, 1, amt >= 8);
612 if (LinkGraph::IsValidID(ge.link_graph)) {
613 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
617 /* Only show a message in case the acceptance was actually changed. */
618 CargoTypes new_acc = GetAcceptanceMask(st);
619 if (old_acc == new_acc) return;
621 /* show a message to report that the acceptance was changed? */
622 if (show_msg && st->owner == _local_company && st->IsInUse()) {
623 /* List of accept and reject strings for different number of
624 * cargo types */
625 static const StringID accept_msg[] = {
626 STR_NEWS_STATION_NOW_ACCEPTS_CARGO,
627 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO,
629 static const StringID reject_msg[] = {
630 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO,
631 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO,
634 /* Array of accepted and rejected cargo types */
635 CargoID accepts[2] = { CT_INVALID, CT_INVALID };
636 CargoID rejects[2] = { CT_INVALID, CT_INVALID };
637 uint num_acc = 0;
638 uint num_rej = 0;
640 /* Test each cargo type to see if its acceptance has changed */
641 for (CargoID i = 0; i < NUM_CARGO; i++) {
642 if (HasBit(new_acc, i)) {
643 if (!HasBit(old_acc, i) && num_acc < lengthof(accepts)) {
644 /* New cargo is accepted */
645 accepts[num_acc++] = i;
647 } else {
648 if (HasBit(old_acc, i) && num_rej < lengthof(rejects)) {
649 /* Old cargo is no longer accepted */
650 rejects[num_rej++] = i;
655 /* Show news message if there are any changes */
656 if (num_acc > 0) ShowRejectOrAcceptNews(st, num_acc, accepts, accept_msg[num_acc - 1]);
657 if (num_rej > 0) ShowRejectOrAcceptNews(st, num_rej, rejects, reject_msg[num_rej - 1]);
660 /* redraw the station view since acceptance changed */
661 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_ACCEPT_RATING_LIST);
664 static void UpdateStationSignCoord(BaseStation *st)
666 const StationRect *r = &st->rect;
668 if (r->IsEmpty()) return; // no tiles belong to this station
670 /* clamp sign coord to be inside the station rect */
671 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
672 st->MoveSign(new_xy);
674 if (!Station::IsExpected(st)) return;
675 Station *full_station = Station::From(st);
676 for (CargoID c = 0; c < NUM_CARGO; ++c) {
677 LinkGraphID lg = full_station->goods[c].link_graph;
678 if (!LinkGraph::IsValidID(lg)) continue;
679 (*LinkGraph::Get(lg))[full_station->goods[c].node].UpdateLocation(st->xy);
684 * Common part of building various station parts and possibly attaching them to an existing one.
685 * @param[in,out] st Station to attach to
686 * @param flags Command flags
687 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
688 * @param area Area occupied by the new part
689 * @param name_class Station naming class to use to generate the new station's name
690 * @return Command error that occurred, if any
692 static CommandCost BuildStationPart(Station **st, DoCommandFlag flags, bool reuse, TileArea area, StationNaming name_class)
694 /* Find a deleted station close to us */
695 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
697 if (*st != nullptr) {
698 if ((*st)->owner != _current_company) {
699 return_cmd_error(CMD_ERROR);
702 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
703 if (ret.Failed()) return ret;
704 } else {
705 /* allocate and initialize new station */
706 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
708 if (flags & DC_EXEC) {
709 *st = new Station(area.tile);
710 _station_kdtree.Insert((*st)->index);
712 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
713 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
715 if (Company::IsValidID(_current_company)) {
716 SetBit((*st)->town->have_ratings, _current_company);
720 return CommandCost();
724 * This is called right after a station was deleted.
725 * It checks if the whole station is free of substations, and if so, the station will be
726 * deleted after a little while.
727 * @param st Station
729 static void DeleteStationIfEmpty(BaseStation *st)
731 if (!st->IsInUse()) {
732 st->delete_ctr = 0;
733 InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
735 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
736 UpdateStationSignCoord(st);
740 * After adding/removing tiles to station, update some station-related stuff.
741 * @param adding True if adding tiles, false if removing them.
742 * @param type StationType being modified.
744 void Station::AfterStationTileSetChange(bool adding, StationType type)
746 this->UpdateVirtCoord();
747 DirtyCompanyInfrastructureWindows(this->owner);
749 if (adding) {
750 this->RecomputeCatchment();
751 MarkCatchmentTilesDirty();
752 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
753 } else {
754 MarkCatchmentTilesDirty();
757 switch (type) {
758 case STATION_RAIL:
759 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_TRAINS);
760 break;
761 case STATION_AIRPORT:
762 break;
763 case STATION_TRUCK:
764 case STATION_BUS:
765 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_ROADVEHS);
766 break;
767 case STATION_DOCK:
768 SetWindowWidgetDirty(WC_STATION_VIEW, this->index, WID_SV_SHIPS);
769 break;
770 default: NOT_REACHED();
773 if (adding) {
774 UpdateStationAcceptance(this, false);
775 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
776 } else {
777 DeleteStationIfEmpty(this);
778 this->RecomputeCatchment();
783 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
786 * Checks if the given tile is buildable, flat and has a certain height.
787 * @param tile TileIndex to check.
788 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
789 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
790 * @param allow_steep Whether steep slopes are allowed.
791 * @param check_bridge Check for the existence of a bridge.
792 * @return The cost in case of success, or an error code if it failed.
794 CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
796 if (check_bridge && IsBridgeAbove(tile)) {
797 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
800 CommandCost ret = EnsureNoVehicleOnGround(tile);
801 if (ret.Failed()) return ret;
803 int z;
804 Slope tileh = GetTileSlope(tile, &z);
806 /* Prohibit building if
807 * 1) The tile is "steep" (i.e. stretches two height levels).
808 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
810 if ((!allow_steep && IsSteepSlope(tileh)) ||
811 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
812 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
815 CommandCost cost(EXPENSES_CONSTRUCTION);
816 int flat_z = z + GetSlopeMaxZ(tileh);
817 if (tileh != SLOPE_FLAT) {
818 /* Forbid building if the tile faces a slope in a invalid direction. */
819 for (DiagDirection dir = DIAGDIR_BEGIN; dir != DIAGDIR_END; dir++) {
820 if (HasBit(invalid_dirs, dir) && !CanBuildDepotByTileh(dir, tileh)) {
821 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
824 cost.AddCost(_price[PR_BUILD_FOUNDATION]);
827 /* The level of this tile must be equal to allowed_z. */
828 if (allowed_z < 0) {
829 /* First tile. */
830 allowed_z = flat_z;
831 } else if (allowed_z != flat_z) {
832 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
835 return cost;
839 * Checks if an airport can be built at the given location and clear the area.
840 * @param tile_iter Airport tile iterator.
841 * @param flags Operation to perform.
842 * @return The cost in case of success, or an error code if it failed.
844 static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlag flags)
846 CommandCost cost(EXPENSES_CONSTRUCTION);
847 int allowed_z = -1;
849 for (; tile_iter != INVALID_TILE; ++tile_iter) {
850 CommandCost ret = CheckBuildableTile(tile_iter, 0, allowed_z, true);
851 if (ret.Failed()) return ret;
852 cost.AddCost(ret);
854 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_iter);
855 if (ret.Failed()) return ret;
856 cost.AddCost(ret);
859 return cost;
863 * Checks if a rail station can be built at the given area.
864 * @param tile_area Area to check.
865 * @param flags Operation to perform.
866 * @param axis Rail station axis.
867 * @param station StationID to be queried and returned if available.
868 * @param rt The rail type to check for (overbuilding rail stations over rail).
869 * @param affected_vehicles List of trains with PBS reservations on the tiles
870 * @param spec_class Station class.
871 * @param spec_index Index into the station class.
872 * @param plat_len Platform length.
873 * @param numtracks Number of platforms.
874 * @return The cost in case of success, or an error code if it failed.
876 static CommandCost CheckFlatLandRailStation(TileArea tile_area, DoCommandFlag flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, byte spec_index, byte plat_len, byte numtracks)
878 CommandCost cost(EXPENSES_CONSTRUCTION);
879 int allowed_z = -1;
880 uint invalid_dirs = 5 << axis;
882 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
883 bool slope_cb = statspec != nullptr && HasBit(statspec->callback_mask, CBM_STATION_SLOPE_CHECK);
885 for (TileIndex tile_cur : tile_area) {
886 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false);
887 if (ret.Failed()) return ret;
888 cost.AddCost(ret);
890 if (slope_cb) {
891 /* Do slope check if requested. */
892 ret = PerformStationTileSlopeCheck(tile_area.tile, tile_cur, statspec, axis, plat_len, numtracks);
893 if (ret.Failed()) return ret;
896 /* if station is set, then we have special handling to allow building on top of already existing stations.
897 * so station points to INVALID_STATION if we can build on any station.
898 * Or it points to a station if we're only allowed to build on exactly that station. */
899 if (station != nullptr && IsTileType(tile_cur, MP_STATION)) {
900 if (!IsRailStation(tile_cur)) {
901 return ClearTile_Station(tile_cur, DC_AUTO); // get error message
902 } else {
903 StationID st = GetStationIndex(tile_cur);
904 if (*station == INVALID_STATION) {
905 *station = st;
906 } else if (*station != st) {
907 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
910 } else {
911 /* Rail type is only valid when building a railway station; if station to
912 * build isn't a rail station it's INVALID_RAILTYPE. */
913 if (rt != INVALID_RAILTYPE &&
914 IsPlainRailTile(tile_cur) && !HasSignals(tile_cur) &&
915 HasPowerOnRail(GetRailType(tile_cur), rt)) {
916 /* Allow overbuilding if the tile:
917 * - has rail, but no signals
918 * - it has exactly one track
919 * - the track is in line with the station
920 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
922 TrackBits tracks = GetTrackBits(tile_cur);
923 Track track = RemoveFirstTrack(&tracks);
924 Track expected_track = HasBit(invalid_dirs, DIAGDIR_NE) ? TRACK_X : TRACK_Y;
926 if (tracks == TRACK_BIT_NONE && track == expected_track) {
927 /* Check for trains having a reservation for this tile. */
928 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
929 Train *v = GetTrainForReservation(tile_cur, track);
930 if (v != nullptr) {
931 affected_vehicles.push_back(v);
934 CommandCost ret = Command<CMD_REMOVE_SINGLE_RAIL>::Do(flags, tile_cur, track);
935 if (ret.Failed()) return ret;
936 cost.AddCost(ret);
937 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
938 continue;
941 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
942 if (ret.Failed()) return ret;
943 cost.AddCost(ret);
947 return cost;
951 * Checks if a road stop can be built at the given tile.
952 * @param tile_area Area to check.
953 * @param flags Operation to perform.
954 * @param invalid_dirs Prohibited directions (set of DiagDirections).
955 * @param is_drive_through True if trying to build a drive-through station.
956 * @param is_truck_stop True when building a truck stop, false otherwise.
957 * @param axis Axis of a drive-through road stop.
958 * @param station StationID to be queried and returned if available.
959 * @param rt Road type to build.
960 * @return The cost in case of success, or an error code if it failed.
962 static CommandCost CheckFlatLandRoadStop(TileArea tile_area, DoCommandFlag flags, uint invalid_dirs, bool is_drive_through, bool is_truck_stop, Axis axis, StationID *station, RoadType rt)
964 CommandCost cost(EXPENSES_CONSTRUCTION);
965 int allowed_z = -1;
967 for (TileIndex cur_tile : tile_area) {
968 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through);
969 if (ret.Failed()) return ret;
970 cost.AddCost(ret);
972 /* If station is set, then we have special handling to allow building on top of already existing stations.
973 * Station points to INVALID_STATION if we can build on any station.
974 * Or it points to a station if we're only allowed to build on exactly that station. */
975 if (station != nullptr && IsTileType(cur_tile, MP_STATION)) {
976 if (!IsRoadStop(cur_tile)) {
977 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
978 } else {
979 if (is_truck_stop != IsTruckStop(cur_tile) ||
980 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
981 return ClearTile_Station(cur_tile, DC_AUTO); // Get error message.
983 /* Drive-through station in the wrong direction. */
984 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && DiagDirToAxis(GetRoadStopDir(cur_tile)) != axis){
985 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
987 StationID st = GetStationIndex(cur_tile);
988 if (*station == INVALID_STATION) {
989 *station = st;
990 } else if (*station != st) {
991 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
994 } else {
995 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
996 /* Road bits in the wrong direction. */
997 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : ROAD_NONE;
998 if (build_over_road && (rb & (axis == AXIS_X ? ROAD_Y : ROAD_X)) != 0) {
999 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1000 switch (CountBits(rb)) {
1001 case 1:
1002 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1004 case 2:
1005 if (rb == ROAD_X || rb == ROAD_Y) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1006 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER);
1008 default: // 3 or 4
1009 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1013 if (build_over_road) {
1014 /* There is a road, check if we can build road+tram stop over it. */
1015 RoadType road_rt = GetRoadType(cur_tile, RTT_ROAD);
1016 if (road_rt != INVALID_ROADTYPE) {
1017 Owner road_owner = GetRoadOwner(cur_tile, RTT_ROAD);
1018 if (road_owner == OWNER_TOWN) {
1019 if (!_settings_game.construction.road_stop_on_town_road) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1020 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1021 CommandCost ret = CheckOwnership(road_owner);
1022 if (ret.Failed()) return ret;
1024 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_ROAD));
1026 if (RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1028 if (GetDisallowedRoadDirections(cur_tile) != DRD_NONE && road_owner != OWNER_TOWN) {
1029 CommandCost ret = CheckOwnership(road_owner);
1030 if (ret.Failed()) return ret;
1033 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1034 } else if (RoadTypeIsRoad(rt)) {
1035 cost.AddCost(RoadBuildCost(rt) * 2);
1038 /* There is a tram, check if we can build road+tram stop over it. */
1039 RoadType tram_rt = GetRoadType(cur_tile, RTT_TRAM);
1040 if (tram_rt != INVALID_ROADTYPE) {
1041 Owner tram_owner = GetRoadOwner(cur_tile, RTT_TRAM);
1042 if (Company::IsValidID(tram_owner) &&
1043 (!_settings_game.construction.road_stop_on_competitor_road ||
1044 /* Disallow breaking end-of-line of someone else
1045 * so trams can still reverse on this tile. */
1046 HasExactlyOneBit(GetRoadBits(cur_tile, RTT_TRAM)))) {
1047 CommandCost ret = CheckOwnership(tram_owner);
1048 if (ret.Failed()) return ret;
1050 uint num_pieces = CountBits(GetRoadBits(cur_tile, RTT_TRAM));
1052 if (RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD);
1054 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1055 } else if (RoadTypeIsTram(rt)) {
1056 cost.AddCost(RoadBuildCost(rt) * 2);
1058 } else {
1059 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, cur_tile);
1060 if (ret.Failed()) return ret;
1061 cost.AddCost(ret);
1062 cost.AddCost(RoadBuildCost(rt) * 2);
1067 return cost;
1071 * Check whether we can expand the rail part of the given station.
1072 * @param st the station to expand
1073 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1074 * @param axis the axis of the newly build rail
1075 * @return Succeeded or failed command.
1077 CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis)
1079 TileArea cur_ta = st->train_station;
1081 /* determine new size of train station region.. */
1082 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1083 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1084 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1085 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1086 new_ta.tile = TileXY(x, y);
1088 /* make sure the final size is not too big. */
1089 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1090 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1093 return CommandCost();
1096 static inline byte *CreateSingle(byte *layout, int n)
1098 int i = n;
1099 do *layout++ = 0; while (--i);
1100 layout[((n - 1) >> 1) - n] = 2;
1101 return layout;
1104 static inline byte *CreateMulti(byte *layout, int n, byte b)
1106 int i = n;
1107 do *layout++ = b; while (--i);
1108 if (n > 4) {
1109 layout[0 - n] = 0;
1110 layout[n - 1 - n] = 0;
1112 return layout;
1116 * Create the station layout for the given number of tracks and platform length.
1117 * @param layout The layout to write to.
1118 * @param numtracks The number of tracks to write.
1119 * @param plat_len The length of the platforms.
1120 * @param statspec The specification of the station to (possibly) get the layout from.
1122 void GetStationLayout(byte *layout, uint numtracks, uint plat_len, const StationSpec *statspec)
1124 if (statspec != nullptr && statspec->layouts.size() >= plat_len &&
1125 statspec->layouts[plat_len - 1].size() >= numtracks &&
1126 !statspec->layouts[plat_len - 1][numtracks - 1].empty()) {
1127 /* Custom layout defined, follow it. */
1128 memcpy(layout, statspec->layouts[plat_len - 1][numtracks - 1].data(),
1129 plat_len * numtracks);
1130 return;
1133 if (plat_len == 1) {
1134 CreateSingle(layout, numtracks);
1135 } else {
1136 if (numtracks & 1) layout = CreateSingle(layout, plat_len);
1137 int n = numtracks >> 1;
1139 while (--n >= 0) {
1140 layout = CreateMulti(layout, plat_len, 4);
1141 layout = CreateMulti(layout, plat_len, 6);
1147 * Find a nearby station that joins this station.
1148 * @tparam T the class to find a station for
1149 * @tparam error_message the error message when building a station on top of others
1150 * @param existing_station an existing station we build over
1151 * @param station_to_join the station to join to
1152 * @param adjacent whether adjacent stations are allowed
1153 * @param ta the area of the newly build station
1154 * @param st 'return' pointer for the found station
1155 * @return command cost with the error or 'okay'
1157 template <class T, StringID error_message>
1158 CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st)
1160 assert(*st == nullptr);
1161 bool check_surrounding = true;
1163 if (_settings_game.station.adjacent_stations) {
1164 if (existing_station != INVALID_STATION) {
1165 if (adjacent && existing_station != station_to_join) {
1166 /* You can't build an adjacent station over the top of one that
1167 * already exists. */
1168 return_cmd_error(error_message);
1169 } else {
1170 /* Extend the current station, and don't check whether it will
1171 * be near any other stations. */
1172 *st = T::GetIfValid(existing_station);
1173 check_surrounding = (*st == nullptr);
1175 } else {
1176 /* There's no station here. Don't check the tiles surrounding this
1177 * one if the company wanted to build an adjacent station. */
1178 if (adjacent) check_surrounding = false;
1182 if (check_surrounding) {
1183 /* Make sure there is no more than one other station around us that is owned by us. */
1184 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st);
1185 if (ret.Failed()) return ret;
1188 /* Distant join */
1189 if (*st == nullptr && station_to_join != INVALID_STATION) *st = T::GetIfValid(station_to_join);
1191 return CommandCost();
1195 * Find a nearby station that joins this station.
1196 * @param existing_station an existing station we build over
1197 * @param station_to_join the station to join to
1198 * @param adjacent whether adjacent stations are allowed
1199 * @param ta the area of the newly build station
1200 * @param st 'return' pointer for the found station
1201 * @return command cost with the error or 'okay'
1203 static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1205 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st);
1209 * Find a nearby waypoint that joins this waypoint.
1210 * @param existing_waypoint an existing waypoint we build over
1211 * @param waypoint_to_join the waypoint to join to
1212 * @param adjacent whether adjacent waypoints are allowed
1213 * @param ta the area of the newly build waypoint
1214 * @param wp 'return' pointer for the found waypoint
1215 * @return command cost with the error or 'okay'
1217 CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp)
1219 return FindJoiningBaseStation<Waypoint, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST>(existing_waypoint, waypoint_to_join, adjacent, ta, wp);
1223 * Clear platform reservation during station building/removing.
1224 * @param v vehicle which holds reservation
1226 static void FreeTrainReservation(Train *v)
1228 FreeTrainTrackReservation(v);
1229 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), false);
1230 v = v->Last();
1231 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), false);
1235 * Restore platform reservation during station building/removing.
1236 * @param v vehicle which held reservation
1238 static void RestoreTrainReservation(Train *v)
1240 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(v->GetVehicleTrackdir()), true);
1241 TryPathReserve(v, true, true);
1242 v = v->Last();
1243 if (IsRailStationTile(v->tile)) SetRailStationPlatformReservation(v->tile, TrackdirToExitdir(ReverseTrackdir(v->GetVehicleTrackdir())), true);
1247 * Build rail station
1248 * @param flags operation to perform
1249 * @param tile_org northern most position of station dragging/placement
1250 * @param rt railtype
1251 * @param axis orientation (Axis)
1252 * @param numtracks number of tracks
1253 * @param plat_len platform length
1254 * @param spec_class custom station class
1255 * @param spec_index custom station id
1256 * @param station_to_join station ID to join (NEW_STATION if build new one)
1257 * @param adjacent allow stations directly adjacent to other stations.
1258 * @return the cost of this operation or an error
1260 CommandCost CmdBuildRailStation(DoCommandFlag flags, TileIndex tile_org, RailType rt, Axis axis, byte numtracks, byte plat_len, StationClassID spec_class, byte spec_index, StationID station_to_join, bool adjacent)
1262 /* Does the authority allow this? */
1263 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1264 if (ret.Failed()) return ret;
1266 if (!ValParamRailtype(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1268 /* Check if the given station class is valid */
1269 if ((uint)spec_class >= StationClass::GetClassCount() || spec_class == STAT_CLASS_WAYP) return CMD_ERROR;
1270 if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR;
1271 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1273 int w_org, h_org;
1274 if (axis == AXIS_X) {
1275 w_org = plat_len;
1276 h_org = numtracks;
1277 } else {
1278 h_org = plat_len;
1279 w_org = numtracks;
1282 bool reuse = (station_to_join != NEW_STATION);
1283 if (!reuse) station_to_join = INVALID_STATION;
1284 bool distant_join = (station_to_join != INVALID_STATION);
1286 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1288 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1290 /* these values are those that will be stored in train_tile and station_platforms */
1291 TileArea new_location(tile_org, w_org, h_org);
1293 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1294 StationID est = INVALID_STATION;
1295 std::vector<Train *> affected_vehicles;
1296 /* Clear the land below the station. */
1297 CommandCost cost = CheckFlatLandRailStation(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1298 if (cost.Failed()) return cost;
1299 /* Add construction expenses. */
1300 cost.AddCost((numtracks * _price[PR_BUILD_STATION_RAIL] + _price[PR_BUILD_STATION_RAIL_LENGTH]) * plat_len);
1301 cost.AddCost(numtracks * plat_len * RailBuildCost(rt));
1303 Station *st = nullptr;
1304 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1305 if (ret.Failed()) return ret;
1307 ret = BuildStationPart(&st, flags, reuse, new_location, STATIONNAMING_RAIL);
1308 if (ret.Failed()) return ret;
1310 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1311 CommandCost ret = CanExpandRailStation(st, new_location, axis);
1312 if (ret.Failed()) return ret;
1315 /* Check if we can allocate a custom stationspec to this station */
1316 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1317 int specindex = AllocateSpecToStation(statspec, st, (flags & DC_EXEC) != 0);
1318 if (specindex == -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS);
1320 if (statspec != nullptr) {
1321 /* Perform NewStation checks */
1323 /* Check if the station size is permitted */
1324 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7)) || HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) {
1325 return CMD_ERROR;
1328 /* Check if the station is buildable */
1329 if (HasBit(statspec->callback_mask, CBM_STATION_AVAIL)) {
1330 uint16 cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1331 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(statspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
1335 if (flags & DC_EXEC) {
1336 TileIndexDiff tile_delta;
1337 byte *layout_ptr;
1338 byte numtracks_orig;
1339 Track track;
1341 st->train_station = new_location;
1342 st->AddFacility(FACIL_TRAIN, new_location.tile);
1344 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1346 if (statspec != nullptr) {
1347 /* Include this station spec's animation trigger bitmask
1348 * in the station's cached copy. */
1349 st->cached_anim_triggers |= statspec->animation.triggers;
1352 tile_delta = (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1353 track = AxisToTrack(axis);
1355 layout_ptr = AllocaM(byte, numtracks * plat_len);
1356 GetStationLayout(layout_ptr, numtracks, plat_len, statspec);
1358 numtracks_orig = numtracks;
1360 Company *c = Company::Get(st->owner);
1361 TileIndex tile_track = tile_org;
1362 do {
1363 TileIndex tile = tile_track;
1364 int w = plat_len;
1365 do {
1366 byte layout = *layout_ptr++;
1367 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1368 /* Check for trains having a reservation for this tile. */
1369 Train *v = GetTrainForReservation(tile, AxisToTrack(GetRailStationAxis(tile)));
1370 if (v != nullptr) {
1371 affected_vehicles.push_back(v);
1372 FreeTrainReservation(v);
1376 /* Railtype can change when overbuilding. */
1377 if (IsRailStationTile(tile)) {
1378 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1379 c->infrastructure.station--;
1382 /* Remove animation if overbuilding */
1383 DeleteAnimatedTile(tile);
1384 byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1385 MakeRailStation(tile, st->owner, st->index, axis, layout & ~1, rt);
1386 /* Free the spec if we overbuild something */
1387 DeallocateSpecFromStation(st, old_specindex);
1389 SetCustomStationSpecIndex(tile, specindex);
1390 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1391 SetAnimationFrame(tile, 0);
1393 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1394 c->infrastructure.station++;
1396 if (statspec != nullptr) {
1397 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1398 uint32 platinfo = GetPlatformInfo(AXIS_X, GetStationGfx(tile), plat_len, numtracks_orig, plat_len - w, numtracks_orig - numtracks, false);
1400 /* As the station is not yet completely finished, the station does not yet exist. */
1401 uint16 callback = GetStationCallback(CBID_STATION_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1402 if (callback != CALLBACK_FAILED) {
1403 if (callback < 8) {
1404 SetStationGfx(tile, (callback & ~1) + axis);
1405 } else {
1406 ErrorUnknownCallbackResult(statspec->grf_prop.grffile->grfid, CBID_STATION_TILE_LAYOUT, callback);
1410 /* Trigger station animation -- after building? */
1411 TriggerStationAnimation(st, tile, SAT_BUILT);
1414 tile += tile_delta;
1415 } while (--w);
1416 AddTrackToSignalBuffer(tile_track, track, _current_company);
1417 YapfNotifyTrackLayoutChange(tile_track, track);
1418 tile_track += tile_delta ^ TileDiffXY(1, 1); // perpendicular to tile_delta
1419 } while (--numtracks);
1421 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1422 /* Restore reservations of trains. */
1423 RestoreTrainReservation(affected_vehicles[i]);
1426 /* Check whether we need to expand the reservation of trains already on the station. */
1427 TileArea update_reservation_area;
1428 if (axis == AXIS_X) {
1429 update_reservation_area = TileArea(tile_org, 1, numtracks_orig);
1430 } else {
1431 update_reservation_area = TileArea(tile_org, numtracks_orig, 1);
1434 for (TileIndex tile : update_reservation_area) {
1435 /* Don't even try to make eye candy parts reserved. */
1436 if (IsStationTileBlocked(tile)) continue;
1438 DiagDirection dir = AxisToDiagDir(axis);
1439 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1440 TileIndex platform_begin = tile;
1441 TileIndex platform_end = tile;
1443 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1444 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1445 platform_begin = next_tile;
1447 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1448 platform_end = next_tile;
1451 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1452 bool reservation = false;
1453 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1454 reservation = HasStationReservation(t);
1457 if (reservation) {
1458 SetRailStationPlatformReservation(platform_begin, dir, true);
1462 st->MarkTilesDirty(false);
1463 st->AfterStationTileSetChange(true, STATION_RAIL);
1466 return cost;
1469 static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1471 restart:
1473 /* too small? */
1474 if (ta.w != 0 && ta.h != 0) {
1475 /* check the left side, x = constant, y changes */
1476 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1477 /* the left side is unused? */
1478 if (++i == ta.h) {
1479 ta.tile += TileDiffXY(1, 0);
1480 ta.w--;
1481 goto restart;
1485 /* check the right side, x = constant, y changes */
1486 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1487 /* the right side is unused? */
1488 if (++i == ta.h) {
1489 ta.w--;
1490 goto restart;
1494 /* check the upper side, y = constant, x changes */
1495 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1496 /* the left side is unused? */
1497 if (++i == ta.w) {
1498 ta.tile += TileDiffXY(0, 1);
1499 ta.h--;
1500 goto restart;
1504 /* check the lower side, y = constant, x changes */
1505 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1506 /* the left side is unused? */
1507 if (++i == ta.w) {
1508 ta.h--;
1509 goto restart;
1512 } else {
1513 ta.Clear();
1516 return ta;
1519 static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1521 return st->TileBelongsToRailStation(tile);
1524 static void MakeRailStationAreaSmaller(BaseStation *st)
1526 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1529 static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1531 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1534 static void MakeShipStationAreaSmaller(Station *st)
1536 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1537 UpdateStationDockingTiles(st);
1541 * Remove a number of tiles from any rail station within the area.
1542 * @param ta the area to clear station tile from.
1543 * @param affected_stations the stations affected.
1544 * @param flags the command flags.
1545 * @param removal_cost the cost for removing the tile, including the rail.
1546 * @param keep_rail whether to keep the rail of the station.
1547 * @tparam T the type of station to remove.
1548 * @return the number of cleared tiles or an error.
1550 template <class T>
1551 CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlag flags, Money removal_cost, bool keep_rail)
1553 /* Count of the number of tiles removed */
1554 int quantity = 0;
1555 CommandCost total_cost(EXPENSES_CONSTRUCTION);
1556 /* Accumulator for the errors seen during clearing. If no errors happen,
1557 * and the quantity is 0 there is no station. Otherwise it will be one
1558 * of the other error that got accumulated. */
1559 CommandCost error;
1561 /* Do the action for every tile into the area */
1562 for (TileIndex tile : ta) {
1563 /* Make sure the specified tile is a rail station */
1564 if (!HasStationTileRail(tile)) continue;
1566 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1567 CommandCost ret = EnsureNoVehicleOnGround(tile);
1568 error.AddCost(ret);
1569 if (ret.Failed()) continue;
1571 /* Check ownership of station */
1572 T *st = T::GetByTile(tile);
1573 if (st == nullptr) continue;
1575 if (_current_company != OWNER_WATER) {
1576 CommandCost ret = CheckOwnership(st->owner);
1577 error.AddCost(ret);
1578 if (ret.Failed()) continue;
1581 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1582 quantity++;
1584 if (keep_rail || IsStationTileBlocked(tile)) {
1585 /* Don't refund the 'steel' of the track when we keep the
1586 * rail, or when the tile didn't have any rail at all. */
1587 total_cost.AddCost(-_price[PR_CLEAR_RAIL]);
1590 if (flags & DC_EXEC) {
1591 /* read variables before the station tile is removed */
1592 uint specindex = GetCustomStationSpecIndex(tile);
1593 Track track = GetRailStationTrack(tile);
1594 Owner owner = GetTileOwner(tile);
1595 RailType rt = GetRailType(tile);
1596 Train *v = nullptr;
1598 if (HasStationReservation(tile)) {
1599 v = GetTrainForReservation(tile, track);
1600 if (v != nullptr) FreeTrainReservation(v);
1603 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1604 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1606 DoClearSquare(tile);
1607 DeleteNewGRFInspectWindow(GSF_STATIONS, tile);
1608 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1609 Company::Get(owner)->infrastructure.station--;
1610 DirtyCompanyInfrastructureWindows(owner);
1612 st->rect.AfterRemoveTile(st, tile);
1613 AddTrackToSignalBuffer(tile, track, owner);
1614 YapfNotifyTrackLayoutChange(tile, track);
1616 DeallocateSpecFromStation(st, specindex);
1618 include(affected_stations, st);
1620 if (v != nullptr) RestoreTrainReservation(v);
1624 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1626 for (T *st : affected_stations) {
1628 /* now we need to make the "spanned" area of the railway station smaller
1629 * if we deleted something at the edges.
1630 * we also need to adjust train_tile. */
1631 MakeRailStationAreaSmaller(st);
1632 UpdateStationSignCoord(st);
1634 /* if we deleted the whole station, delete the train facility. */
1635 if (st->train_station.tile == INVALID_TILE) {
1636 st->facilities &= ~FACIL_TRAIN;
1637 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1638 MarkCatchmentTilesDirty();
1639 st->UpdateVirtCoord();
1640 DeleteStationIfEmpty(st);
1644 total_cost.AddCost(quantity * removal_cost);
1645 return total_cost;
1649 * Remove a single tile from a rail station.
1650 * This allows for custom-built station with holes and weird layouts
1651 * @param flags operation to perform
1652 * @param start tile of station piece to remove
1653 * @param end other edge of the rect to remove
1654 * @param keep_rail if set keep the rail
1655 * @return the cost of this operation or an error
1657 CommandCost CmdRemoveFromRailStation(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1659 if (end == 0) end = start;
1660 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1662 TileArea ta(start, end);
1663 std::vector<Station *> affected_stations;
1665 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_STATION_RAIL], keep_rail);
1666 if (ret.Failed()) return ret;
1668 /* Do all station specific functions here. */
1669 for (Station *st : affected_stations) {
1671 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_TRAINS);
1672 st->MarkTilesDirty(false);
1673 MarkCatchmentTilesDirty();
1674 st->RecomputeCatchment();
1677 /* Now apply the rail cost to the number that we deleted */
1678 return ret;
1682 * Remove a single tile from a waypoint.
1683 * This allows for custom-built waypoint with holes and weird layouts
1684 * @param flags operation to perform
1685 * @param start tile of waypoint piece to remove
1686 * @param end other edge of the rect to remove
1687 * @param keep_rail if set keep the rail
1688 * @return the cost of this operation or an error
1690 CommandCost CmdRemoveFromRailWaypoint(DoCommandFlag flags, TileIndex start, TileIndex end, bool keep_rail)
1692 if (end == 0) end = start;
1693 if (start >= MapSize() || end >= MapSize()) return CMD_ERROR;
1695 TileArea ta(start, end);
1696 std::vector<Waypoint *> affected_stations;
1698 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[PR_CLEAR_WAYPOINT_RAIL], keep_rail);
1703 * Remove a rail station/waypoint
1704 * @param st The station/waypoint to remove the rail part from
1705 * @param flags operation to perform
1706 * @param removal_cost the cost for removing a tile
1707 * @tparam T the type of station to remove
1708 * @return cost or failure of operation
1710 template <class T>
1711 CommandCost RemoveRailStation(T *st, DoCommandFlag flags, Money removal_cost)
1713 /* Current company owns the station? */
1714 if (_current_company != OWNER_WATER) {
1715 CommandCost ret = CheckOwnership(st->owner);
1716 if (ret.Failed()) return ret;
1719 /* determine width and height of platforms */
1720 TileArea ta = st->train_station;
1722 assert(ta.w != 0 && ta.h != 0);
1724 CommandCost cost(EXPENSES_CONSTRUCTION);
1725 /* clear all areas of the station */
1726 for (TileIndex tile : ta) {
1727 /* only remove tiles that are actually train station tiles */
1728 if (st->TileBelongsToRailStation(tile)) {
1729 std::vector<T*> affected_stations; // dummy
1730 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1731 if (ret.Failed()) return ret;
1732 cost.AddCost(ret);
1736 return cost;
1740 * Remove a rail station
1741 * @param tile Tile of the station.
1742 * @param flags operation to perform
1743 * @return cost or failure of operation
1745 static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlag flags)
1747 /* if there is flooding, remove platforms tile by tile */
1748 if (_current_company == OWNER_WATER) {
1749 return Command<CMD_REMOVE_FROM_RAIL_STATION>::Do(DC_EXEC, tile, 0, false);
1752 Station *st = Station::GetByTile(tile);
1753 CommandCost cost = RemoveRailStation(st, flags, _price[PR_CLEAR_STATION_RAIL]);
1755 if (flags & DC_EXEC) st->RecomputeCatchment();
1757 return cost;
1761 * Remove a rail waypoint
1762 * @param tile Tile of the waypoint.
1763 * @param flags operation to perform
1764 * @return cost or failure of operation
1766 static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlag flags)
1768 /* if there is flooding, remove waypoints tile by tile */
1769 if (_current_company == OWNER_WATER) {
1770 return Command<CMD_REMOVE_FROM_RAIL_WAYPOINT>::Do(DC_EXEC, tile, 0, false);
1773 return RemoveRailStation(Waypoint::GetByTile(tile), flags, _price[PR_CLEAR_WAYPOINT_RAIL]);
1778 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1779 * @param st The Station to do the whole procedure for
1780 * @return a pointer to where to link a new RoadStop*
1782 static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1784 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1786 if (*primary_stop == nullptr) {
1787 /* we have no roadstop of the type yet, so write a "primary stop" */
1788 return primary_stop;
1789 } else {
1790 /* there are stops already, so append to the end of the list */
1791 RoadStop *stop = *primary_stop;
1792 while (stop->next != nullptr) stop = stop->next;
1793 return &stop->next;
1797 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags);
1800 * Find a nearby station that joins this road stop.
1801 * @param existing_stop an existing road stop we build over
1802 * @param station_to_join the station to join to
1803 * @param adjacent whether adjacent stations are allowed
1804 * @param ta the area of the newly build station
1805 * @param st 'return' pointer for the found station
1806 * @return command cost with the error or 'okay'
1808 static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1810 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st);
1814 * Build a bus or truck stop.
1815 * @param flags Operation to perform.
1816 * @param tile Northernmost tile of the stop.
1817 * @param width Width of the road stop.
1818 * @param length Length of the road stop.
1819 * @param stop_type Type of road stop (bus/truck).
1820 * @param is_drive_through False for normal stops, true for drive-through.
1821 * @param ddir Entrance direction (#DiagDirection) for normal stops. Converted to the axis for drive-through stops.
1822 * @param rt The roadtype.
1823 * @param station_to_join Station ID to join (NEW_STATION if build new one).
1824 * @param adjacent Allow stations directly adjacent to other stations.
1825 * @return The cost of this operation or an error.
1827 CommandCost CmdBuildRoadStop(DoCommandFlag flags, TileIndex tile, uint8 width, uint8 length, RoadStopType stop_type, bool is_drive_through, DiagDirection ddir, RoadType rt, StationID station_to_join, bool adjacent)
1829 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= ROADSTOP_END) return CMD_ERROR;
1830 bool reuse = (station_to_join != NEW_STATION);
1831 if (!reuse) station_to_join = INVALID_STATION;
1832 bool distant_join = (station_to_join != INVALID_STATION);
1834 /* Check if the requested road stop is too big */
1835 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
1836 /* Check for incorrect width / length. */
1837 if (width == 0 || length == 0) return CMD_ERROR;
1838 /* Check if the first tile and the last tile are valid */
1839 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
1841 TileArea roadstop_area(tile, width, length);
1843 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1845 /* Trams only have drive through stops */
1846 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
1848 Axis axis = DiagDirToAxis(ddir);
1850 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
1851 if (ret.Failed()) return ret;
1853 bool is_truck_stop = stop_type != ROADSTOP_BUS;
1855 /* Total road stop cost. */
1856 CommandCost cost(EXPENSES_CONSTRUCTION, roadstop_area.w * roadstop_area.h * _price[is_truck_stop ? PR_BUILD_STATION_TRUCK : PR_BUILD_STATION_BUS]);
1857 StationID est = INVALID_STATION;
1858 ret = CheckFlatLandRoadStop(roadstop_area, flags, is_drive_through ? 5 << axis : 1 << ddir, is_drive_through, is_truck_stop, axis, &est, rt);
1859 if (ret.Failed()) return ret;
1860 cost.AddCost(ret);
1862 Station *st = nullptr;
1863 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
1864 if (ret.Failed()) return ret;
1866 /* Check if this number of road stops can be allocated. */
1867 if (!RoadStop::CanAllocateItem(roadstop_area.w * roadstop_area.h)) return_cmd_error(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
1869 ret = BuildStationPart(&st, flags, reuse, roadstop_area, STATIONNAMING_ROAD);
1870 if (ret.Failed()) return ret;
1872 if (flags & DC_EXEC) {
1873 /* Check every tile in the area. */
1874 for (TileIndex cur_tile : roadstop_area) {
1875 /* Get existing road types and owners before any tile clearing */
1876 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_ROAD) : INVALID_ROADTYPE;
1877 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RTT_TRAM) : INVALID_ROADTYPE;
1878 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_ROAD) : _current_company;
1879 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RTT_TRAM) : _current_company;
1881 if (IsTileType(cur_tile, MP_STATION) && IsRoadStop(cur_tile)) {
1882 RemoveRoadStop(cur_tile, flags);
1885 RoadStop *road_stop = new RoadStop(cur_tile);
1886 /* Insert into linked list of RoadStops. */
1887 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
1888 *currstop = road_stop;
1890 if (is_truck_stop) {
1891 st->truck_station.Add(cur_tile);
1892 } else {
1893 st->bus_station.Add(cur_tile);
1896 /* Initialize an empty station. */
1897 st->AddFacility(is_truck_stop ? FACIL_TRUCK_STOP : FACIL_BUS_STOP, cur_tile);
1899 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
1901 RoadStopType rs_type = is_truck_stop ? ROADSTOP_TRUCK : ROADSTOP_BUS;
1902 if (is_drive_through) {
1903 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
1904 * bits first. */
1905 if (IsNormalRoadTile(cur_tile)) {
1906 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_ROAD)));
1907 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -(int)CountBits(GetRoadBits(cur_tile, RTT_TRAM)));
1910 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
1911 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
1913 UpdateCompanyRoadInfrastructure(road_rt, road_owner, ROAD_STOP_TRACKBIT_FACTOR);
1914 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, ROAD_STOP_TRACKBIT_FACTOR);
1916 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, rs_type, road_rt, tram_rt, axis);
1917 road_stop->MakeDriveThrough();
1918 } else {
1919 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
1920 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
1921 /* Non-drive-through stop never overbuild and always count as two road bits. */
1922 Company::Get(st->owner)->infrastructure.road[rt] += ROAD_STOP_TRACKBIT_FACTOR;
1923 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
1925 Company::Get(st->owner)->infrastructure.station++;
1927 MarkTileDirtyByTile(cur_tile);
1930 if (st != nullptr) {
1931 st->AfterStationTileSetChange(true, is_truck_stop ? STATION_TRUCK: STATION_BUS);
1934 return cost;
1938 static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
1940 if (v->type == VEH_ROAD) {
1941 /* Okay... we are a road vehicle on a drive through road stop.
1942 * But that road stop has just been removed, so we need to make
1943 * sure we are in a valid state... however, vehicles can also
1944 * turn on road stop tiles, so only clear the 'road stop' state
1945 * bits and only when the state was 'in road stop', otherwise
1946 * we'll end up clearing the turn around bits. */
1947 RoadVehicle *rv = RoadVehicle::From(v);
1948 if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) rv->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
1951 return nullptr;
1956 * Remove a bus station/truck stop
1957 * @param tile TileIndex been queried
1958 * @param flags operation to perform
1959 * @return cost or failure of operation
1961 static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags)
1963 Station *st = Station::GetByTile(tile);
1965 if (_current_company != OWNER_WATER) {
1966 CommandCost ret = CheckOwnership(st->owner);
1967 if (ret.Failed()) return ret;
1970 bool is_truck = IsTruckStop(tile);
1972 RoadStop **primary_stop;
1973 RoadStop *cur_stop;
1974 if (is_truck) { // truck stop
1975 primary_stop = &st->truck_stops;
1976 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_TRUCK);
1977 } else {
1978 primary_stop = &st->bus_stops;
1979 cur_stop = RoadStop::GetByTile(tile, ROADSTOP_BUS);
1982 assert(cur_stop != nullptr);
1984 /* don't do the check for drive-through road stops when company bankrupts */
1985 if (IsDriveThroughStopTile(tile) && (flags & DC_BANKRUPT)) {
1986 /* remove the 'going through road stop' status from all vehicles on that tile */
1987 if (flags & DC_EXEC) FindVehicleOnPos(tile, nullptr, &ClearRoadStopStatusEnum);
1988 } else {
1989 CommandCost ret = EnsureNoVehicleOnGround(tile);
1990 if (ret.Failed()) return ret;
1993 if (flags & DC_EXEC) {
1994 if (*primary_stop == cur_stop) {
1995 /* removed the first stop in the list */
1996 *primary_stop = cur_stop->next;
1997 /* removed the only stop? */
1998 if (*primary_stop == nullptr) {
1999 st->facilities &= (is_truck ? ~FACIL_TRUCK_STOP : ~FACIL_BUS_STOP);
2001 } else {
2002 /* tell the predecessor in the list to skip this stop */
2003 RoadStop *pred = *primary_stop;
2004 while (pred->next != cur_stop) pred = pred->next;
2005 pred->next = cur_stop->next;
2008 /* Update company infrastructure counts. */
2009 for (RoadTramType rtt : _roadtramtypes) {
2010 RoadType rt = GetRoadType(tile, rtt);
2011 UpdateCompanyRoadInfrastructure(rt, GetRoadOwner(tile, rtt), -static_cast<int>(ROAD_STOP_TRACKBIT_FACTOR));
2014 Company::Get(st->owner)->infrastructure.station--;
2015 DirtyCompanyInfrastructureWindows(st->owner);
2017 if (IsDriveThroughStopTile(tile)) {
2018 /* Clears the tile for us */
2019 cur_stop->ClearDriveThrough();
2020 } else {
2021 DoClearSquare(tile);
2024 delete cur_stop;
2026 /* Make sure no vehicle is going to the old roadstop */
2027 for (RoadVehicle *v : RoadVehicle::Iterate()) {
2028 if (v->First() == v && v->current_order.IsType(OT_GOTO_STATION) &&
2029 v->dest_tile == tile) {
2030 v->SetDestTile(v->GetOrderStationLocation(st->index));
2034 st->rect.AfterRemoveTile(st, tile);
2036 st->AfterStationTileSetChange(false, is_truck ? STATION_TRUCK: STATION_BUS);
2038 /* Update the tile area of the truck/bus stop */
2039 if (is_truck) {
2040 st->truck_station.Clear();
2041 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2042 } else {
2043 st->bus_station.Clear();
2044 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2048 return CommandCost(EXPENSES_CONSTRUCTION, _price[is_truck ? PR_CLEAR_STATION_TRUCK : PR_CLEAR_STATION_BUS]);
2052 * Remove bus or truck stops.
2053 * @param flags Operation to perform.
2054 * @param tile Northernmost tile of the removal area.
2055 * @param width Width of the removal area.
2056 * @param height Height of the removal area.
2057 * @param stop_type Type of stop (bus/truck).
2058 * @param remove_road Remove roads of drive-through stops?
2059 * @return The cost of this operation or an error.
2061 CommandCost CmdRemoveRoadStop(DoCommandFlag flags, TileIndex tile, uint8 width, uint8 height, RoadStopType stop_type, bool remove_road)
2063 if (stop_type >= ROADSTOP_END) return CMD_ERROR;
2064 /* Check for incorrect width / height. */
2065 if (width == 0 || height == 0) return CMD_ERROR;
2066 /* Check if the first tile and the last tile are valid */
2067 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2068 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2069 if (remove_road && (flags & DC_BANKRUPT)) return CMD_ERROR;
2071 TileArea roadstop_area(tile, width, height);
2073 CommandCost cost(EXPENSES_CONSTRUCTION);
2074 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2075 bool had_success = false;
2077 for (TileIndex cur_tile : roadstop_area) {
2078 /* Make sure the specified tile is a road stop of the correct type */
2079 if (!IsTileType(cur_tile, MP_STATION) || !IsRoadStop(cur_tile) || GetRoadStopType(cur_tile) != stop_type) continue;
2081 /* Save information on to-be-restored roads before the stop is removed. */
2082 RoadBits road_bits = ROAD_NONE;
2083 RoadType road_type[] = { INVALID_ROADTYPE, INVALID_ROADTYPE };
2084 Owner road_owner[] = { OWNER_NONE, OWNER_NONE };
2085 if (IsDriveThroughStopTile(cur_tile)) {
2086 for (RoadTramType rtt : _roadtramtypes) {
2087 road_type[rtt] = GetRoadType(cur_tile, rtt);
2088 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2089 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2090 /* If we don't want to preserve our roads then restore only roads of others. */
2091 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2093 road_bits = AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile)));
2096 CommandCost ret = RemoveRoadStop(cur_tile, flags);
2097 if (ret.Failed()) {
2098 last_error = ret;
2099 continue;
2101 cost.AddCost(ret);
2102 had_success = true;
2104 /* Restore roads. */
2105 if ((flags & DC_EXEC) && (road_type[RTT_ROAD] != INVALID_ROADTYPE || road_type[RTT_TRAM] != INVALID_ROADTYPE)) {
2106 MakeRoadNormal(cur_tile, road_bits, road_type[RTT_ROAD], road_type[RTT_TRAM], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2107 road_owner[RTT_ROAD], road_owner[RTT_TRAM]);
2109 /* Update company infrastructure counts. */
2110 int count = CountBits(road_bits);
2111 UpdateCompanyRoadInfrastructure(road_type[RTT_ROAD], road_owner[RTT_ROAD], count);
2112 UpdateCompanyRoadInfrastructure(road_type[RTT_TRAM], road_owner[RTT_TRAM], count);
2116 return had_success ? cost : last_error;
2120 * Get a possible noise reduction factor based on distance from town center.
2121 * The further you get, the less noise you generate.
2122 * So all those folks at city council can now happily slee... work in their offices
2123 * @param as airport information
2124 * @param distance minimum distance between town and airport
2125 * @return the noise that will be generated, according to distance
2127 uint8 GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2129 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2130 * So no need to go any further*/
2131 if (as->noise_level < 2) return as->noise_level;
2133 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2134 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2135 * Basically, it says that the less tolerant a town is, the bigger the distance before
2136 * an actual decrease can be granted */
2137 uint8 town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2139 /* now, we want to have the distance segmented using the distance judged bareable by town
2140 * This will give us the coefficient of reduction the distance provides. */
2141 uint noise_reduction = distance / town_tolerance_distance;
2143 /* If the noise reduction equals the airport noise itself, don't give it for free.
2144 * Otherwise, simply reduce the airport's level. */
2145 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2149 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2150 * If two towns have the same distance, town with lower index is returned.
2151 * @param as airport's description
2152 * @param it An iterator over all airport tiles
2153 * @param[out] mindist Minimum distance to town
2154 * @return nearest town to airport
2156 Town *AirportGetNearestTown(const AirportSpec *as, const TileIterator &it, uint &mindist)
2158 assert(Town::GetNumItems() > 0);
2160 Town *nearest = nullptr;
2162 uint perimeter_min_x = TileX(it);
2163 uint perimeter_min_y = TileY(it);
2164 uint perimeter_max_x = perimeter_min_x + as->size_x - 1;
2165 uint perimeter_max_y = perimeter_min_y + as->size_y - 1;
2167 mindist = UINT_MAX - 1; // prevent overflow
2169 std::unique_ptr<TileIterator> copy(it.Clone());
2170 for (TileIndex cur_tile = *copy; cur_tile != INVALID_TILE; cur_tile = ++*copy) {
2171 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) {
2172 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2173 if (t == nullptr) continue;
2175 uint dist = DistanceManhattan(t->xy, cur_tile);
2176 if (dist == mindist && t->index < nearest->index) nearest = t;
2177 if (dist < mindist) {
2178 nearest = t;
2179 mindist = dist;
2184 return nearest;
2188 /** Recalculate the noise generated by the airports of each town */
2189 void UpdateAirportsNoise()
2191 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2193 for (const Station *st : Station::Iterate()) {
2194 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2195 const AirportSpec *as = st->airport.GetSpec();
2196 AirportTileIterator it(st);
2197 uint dist;
2198 Town *nearest = AirportGetNearestTown(as, it, dist);
2199 nearest->noise_reached += GetAirportNoiseLevelForDistance(as, dist);
2205 * Place an Airport.
2206 * @param flags operation to perform
2207 * @param tile tile where airport will be built
2208 * @param airport_type airport type, @see airport.h
2209 * @param layout airport layout
2210 * @param station_to_join station ID to join (NEW_STATION if build new one)
2211 * @param allow_adjacent allow airports directly adjacent to other airports.
2212 * @return the cost of this operation or an error
2214 CommandCost CmdBuildAirport(DoCommandFlag flags, TileIndex tile, byte airport_type, byte layout, StationID station_to_join, bool allow_adjacent)
2216 bool reuse = (station_to_join != NEW_STATION);
2217 if (!reuse) station_to_join = INVALID_STATION;
2218 bool distant_join = (station_to_join != INVALID_STATION);
2220 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2222 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2224 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2225 if (ret.Failed()) return ret;
2227 /* Check if a valid, buildable airport was chosen for construction */
2228 const AirportSpec *as = AirportSpec::Get(airport_type);
2229 if (!as->IsAvailable() || layout >= as->num_table) return CMD_ERROR;
2230 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2232 Direction rotation = as->rotation[layout];
2233 int w = as->size_x;
2234 int h = as->size_y;
2235 if (rotation == DIR_E || rotation == DIR_W) Swap(w, h);
2236 TileArea airport_area = TileArea(tile, w, h);
2238 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2239 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
2242 AirportTileTableIterator iter(as->table[layout], tile);
2243 CommandCost cost = CheckFlatLandAirport(iter, flags);
2244 if (cost.Failed()) return cost;
2246 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2247 uint dist;
2248 Town *nearest = AirportGetNearestTown(as, iter, dist);
2249 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2251 /* Check if local auth would allow a new airport */
2252 StringID authority_refuse_message = STR_NULL;
2253 Town *authority_refuse_town = nullptr;
2255 if (_settings_game.economy.station_noise_level) {
2256 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2257 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2258 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2259 authority_refuse_town = nearest;
2261 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2262 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2263 uint num = 0;
2264 for (const Station *st : Station::Iterate()) {
2265 if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport.type != AT_OILRIG) num++;
2267 if (num >= 2) {
2268 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2269 authority_refuse_town = t;
2273 if (authority_refuse_message != STR_NULL) {
2274 SetDParam(0, authority_refuse_town->index);
2275 return_cmd_error(authority_refuse_message);
2278 Station *st = nullptr;
2279 ret = FindJoiningStation(INVALID_STATION, station_to_join, allow_adjacent, airport_area, &st);
2280 if (ret.Failed()) return ret;
2282 /* Distant join */
2283 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2285 ret = BuildStationPart(&st, flags, reuse, airport_area, (GetAirport(airport_type)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_AIRPORT : STATIONNAMING_HELIPORT);
2286 if (ret.Failed()) return ret;
2288 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2289 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2292 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2293 cost.AddCost(_price[PR_BUILD_STATION_AIRPORT]);
2296 if (flags & DC_EXEC) {
2297 /* Always add the noise, so there will be no need to recalculate when option toggles */
2298 nearest->noise_reached += newnoise_level;
2300 st->AddFacility(FACIL_AIRPORT, tile);
2301 st->airport.type = airport_type;
2302 st->airport.layout = layout;
2303 st->airport.flags = 0;
2304 st->airport.rotation = rotation;
2306 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2308 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2309 MakeAirport(iter, st->owner, st->index, iter.GetStationGfx(), WATER_CLASS_INVALID);
2310 SetStationTileRandomBits(iter, GB(Random(), 0, 4));
2311 st->airport.Add(iter);
2313 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(iter);
2316 /* Only call the animation trigger after all tiles have been built */
2317 for (AirportTileTableIterator iter(as->table[layout], tile); iter != INVALID_TILE; ++iter) {
2318 AirportTileAnimationTrigger(st, iter, AAT_BUILT);
2321 UpdateAirplanesOnNewStation(st);
2323 Company::Get(st->owner)->infrastructure.airport++;
2325 st->AfterStationTileSetChange(true, STATION_AIRPORT);
2326 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2328 if (_settings_game.economy.station_noise_level) {
2329 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2333 return cost;
2337 * Remove an airport
2338 * @param tile TileIndex been queried
2339 * @param flags operation to perform
2340 * @return cost or failure of operation
2342 static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
2344 Station *st = Station::GetByTile(tile);
2346 if (_current_company != OWNER_WATER) {
2347 CommandCost ret = CheckOwnership(st->owner);
2348 if (ret.Failed()) return ret;
2351 tile = st->airport.tile;
2353 CommandCost cost(EXPENSES_CONSTRUCTION);
2355 for (const Aircraft *a : Aircraft::Iterate()) {
2356 if (!a->IsNormalAircraft()) continue;
2357 if (a->targetairport == st->index && a->state != FLYING) {
2358 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2362 if (flags & DC_EXEC) {
2363 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2364 TileIndex tile_cur = st->airport.GetHangarTile(i);
2365 OrderBackup::Reset(tile_cur, false);
2366 CloseWindowById(WC_VEHICLE_DEPOT, tile_cur);
2369 const AirportSpec *as = st->airport.GetSpec();
2370 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2371 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2372 * need of recalculation */
2373 AirportTileIterator it(st);
2374 uint dist;
2375 Town *nearest = AirportGetNearestTown(as, it, dist);
2376 nearest->noise_reached -= GetAirportNoiseLevelForDistance(as, dist);
2378 if (_settings_game.economy.station_noise_level) {
2379 SetWindowDirty(WC_TOWN_VIEW, nearest->index);
2383 for (TileIndex tile_cur : st->airport) {
2384 if (!st->TileBelongsToAirport(tile_cur)) continue;
2386 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2387 if (ret.Failed()) return ret;
2389 cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
2391 if (flags & DC_EXEC) {
2392 DeleteAnimatedTile(tile_cur);
2393 DoClearSquare(tile_cur);
2394 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES, tile_cur);
2398 if (flags & DC_EXEC) {
2399 /* Clear the persistent storage. */
2400 delete st->airport.psa;
2402 st->rect.AfterRemoveRect(st, st->airport);
2404 st->airport.Clear();
2405 st->facilities &= ~FACIL_AIRPORT;
2407 InvalidateWindowData(WC_STATION_VIEW, st->index, -1);
2409 Company::Get(st->owner)->infrastructure.airport--;
2411 st->AfterStationTileSetChange(false, STATION_AIRPORT);
2413 DeleteNewGRFInspectWindow(GSF_AIRPORTS, st->index);
2416 return cost;
2420 * Open/close an airport to incoming aircraft.
2421 * @param flags Operation to perform.
2422 * @param station_id Station ID of the airport.
2423 * @return the cost of this operation or an error
2425 CommandCost CmdOpenCloseAirport(DoCommandFlag flags, StationID station_id)
2427 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2428 Station *st = Station::Get(station_id);
2430 if (!(st->facilities & FACIL_AIRPORT) || st->owner == OWNER_NONE) return CMD_ERROR;
2432 CommandCost ret = CheckOwnership(st->owner);
2433 if (ret.Failed()) return ret;
2435 if (flags & DC_EXEC) {
2436 st->airport.flags ^= AIRPORT_CLOSED_block;
2437 SetWindowWidgetDirty(WC_STATION_VIEW, st->index, WID_SV_CLOSE_AIRPORT);
2439 return CommandCost();
2443 * Tests whether the company's vehicles have this station in orders
2444 * @param station station ID
2445 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2446 * @param company company ID
2448 bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2450 for (const Vehicle *v : Vehicle::Iterate()) {
2451 if ((v->owner == company) == include_company) {
2452 for (const Order *order : v->Orders()) {
2453 if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
2454 return true;
2459 return false;
2462 static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
2463 {-1, 0},
2464 { 0, 0},
2465 { 0, 0},
2466 { 0, -1}
2468 static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
2469 static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
2472 * Build a dock/haven.
2473 * @param flags operation to perform
2474 * @param tile tile where dock will be built
2475 * @param station_to_join station ID to join (NEW_STATION if build new one)
2476 * @param adjacent allow docks directly adjacent to other docks.
2477 * @return the cost of this operation or an error
2479 CommandCost CmdBuildDock(DoCommandFlag flags, TileIndex tile, StationID station_to_join, bool adjacent)
2481 bool reuse = (station_to_join != NEW_STATION);
2482 if (!reuse) station_to_join = INVALID_STATION;
2483 bool distant_join = (station_to_join != INVALID_STATION);
2485 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2487 DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile));
2488 if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2489 direction = ReverseDiagDir(direction);
2491 /* Docks cannot be placed on rapids */
2492 if (HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2494 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
2495 if (ret.Failed()) return ret;
2497 if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2499 CommandCost cost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
2500 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
2501 if (ret.Failed()) return ret;
2502 cost.AddCost(ret);
2504 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2506 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2507 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2510 if (IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
2512 /* Get the water class of the water tile before it is cleared.*/
2513 WaterClass wc = GetWaterClass(tile_cur);
2515 ret = Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile_cur);
2516 if (ret.Failed()) return ret;
2518 tile_cur += TileOffsByDiagDir(direction);
2519 if (!IsTileType(tile_cur, MP_WATER) || !IsTileFlat(tile_cur)) {
2520 return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
2523 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2524 _dock_w_chk[direction], _dock_h_chk[direction]);
2526 /* middle */
2527 Station *st = nullptr;
2528 ret = FindJoiningStation(INVALID_STATION, station_to_join, adjacent, dock_area, &st);
2529 if (ret.Failed()) return ret;
2531 /* Distant join */
2532 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2534 ret = BuildStationPart(&st, flags, reuse, dock_area, STATIONNAMING_DOCK);
2535 if (ret.Failed()) return ret;
2537 if (flags & DC_EXEC) {
2538 st->ship_station.Add(tile);
2539 st->ship_station.Add(tile + TileOffsByDiagDir(direction));
2540 st->AddFacility(FACIL_DOCK, tile);
2542 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2544 /* If the water part of the dock is on a canal, update infrastructure counts.
2545 * This is needed as we've unconditionally cleared that tile before. */
2546 if (wc == WATER_CLASS_CANAL) {
2547 Company::Get(st->owner)->infrastructure.water++;
2549 Company::Get(st->owner)->infrastructure.station += 2;
2551 MakeDock(tile, st->owner, st->index, direction, wc);
2552 UpdateStationDockingTiles(st);
2554 st->AfterStationTileSetChange(true, STATION_DOCK);
2557 return cost;
2560 void RemoveDockingTile(TileIndex t)
2562 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2563 TileIndex tile = t + TileOffsByDiagDir(d);
2564 if (!IsValidTile(tile)) continue;
2566 if (IsTileType(tile, MP_STATION)) {
2567 Station *st = Station::GetByTile(tile);
2568 if (st != nullptr) UpdateStationDockingTiles(st);
2569 } else if (IsTileType(tile, MP_INDUSTRY)) {
2570 Station *neutral = Industry::GetByTile(tile)->neutral_station;
2571 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2577 * Clear docking tile status from tiles around a removed dock, if the tile has
2578 * no neighbours which would keep it as a docking tile.
2579 * @param tile Ex-dock tile to check.
2581 void ClearDockingTilesCheckingNeighbours(TileIndex tile)
2583 assert(IsValidTile(tile));
2585 /* Clear and maybe re-set docking tile */
2586 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2587 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
2588 if (!IsValidTile(docking_tile)) continue;
2590 if (IsPossibleDockingTile(docking_tile)) {
2591 SetDockingTile(docking_tile, false);
2592 CheckForDockingTile(docking_tile);
2598 * Check if a dock tile can be docked from the given direction.
2599 * @param t Tile index of dock.
2600 * @param d DiagDirection adjacent to dock being tested. (unused)
2601 * @return True iff the dock can be docked from the given direction.
2603 bool IsValidDockingDirectionForDock(TileIndex t, DiagDirection d)
2605 assert(IsDockTile(t));
2607 StationGfx gfx = GetStationGfx(t);
2608 return gfx >= GFX_DOCK_BASE_WATER_PART;
2612 * Find the part of a dock that is land-based
2613 * @param t Dock tile to find land part of
2614 * @return tile of land part of dock
2616 static TileIndex FindDockLandPart(TileIndex t)
2618 assert(IsDockTile(t));
2620 StationGfx gfx = GetStationGfx(t);
2621 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
2623 for (DiagDirection d = DIAGDIR_BEGIN; d != DIAGDIR_END; d++) {
2624 TileIndex tile = t + TileOffsByDiagDir(d);
2625 if (!IsValidTile(tile)) continue;
2626 if (!IsDockTile(tile)) continue;
2627 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
2630 return INVALID_TILE;
2634 * Remove a dock
2635 * @param tile TileIndex been queried
2636 * @param flags operation to perform
2637 * @return cost or failure of operation
2639 static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
2641 Station *st = Station::GetByTile(tile);
2642 CommandCost ret = CheckOwnership(st->owner);
2643 if (ret.Failed()) return ret;
2645 if (!IsDockTile(tile)) return CMD_ERROR;
2647 TileIndex tile1 = FindDockLandPart(tile);
2648 if (tile1 == INVALID_TILE) return CMD_ERROR;
2649 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
2651 ret = EnsureNoVehicleOnGround(tile1);
2652 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
2653 if (ret.Failed()) return ret;
2655 if (flags & DC_EXEC) {
2656 DoClearSquare(tile1);
2657 MarkTileDirtyByTile(tile1);
2658 MakeWaterKeepingClass(tile2, st->owner);
2660 st->rect.AfterRemoveTile(st, tile1);
2661 st->rect.AfterRemoveTile(st, tile2);
2663 MakeShipStationAreaSmaller(st);
2664 if (st->ship_station.tile == INVALID_TILE) {
2665 st->ship_station.Clear();
2666 st->docking_station.Clear();
2667 st->facilities &= ~FACIL_DOCK;
2670 Company::Get(st->owner)->infrastructure.station -= 2;
2672 st->AfterStationTileSetChange(false, STATION_DOCK);
2674 ClearDockingTilesCheckingNeighbours(tile1);
2675 ClearDockingTilesCheckingNeighbours(tile2);
2677 for (Ship *s : Ship::Iterate()) {
2678 /* Find all ships going to our dock. */
2679 if (s->current_order.GetDestination() != st->index) {
2680 continue;
2683 /* Find ships that are marked as "loading" but are no longer on a
2684 * docking tile. Force them to leave the station (as they were loading
2685 * on the removed dock). */
2686 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
2687 s->LeaveStation();
2690 /* If we no longer have a dock, mark the order as invalid and send
2691 * the ship to the next order (or, if there is none, make it
2692 * wander the world). */
2693 if (s->current_order.IsType(OT_GOTO_STATION) && !(st->facilities & FACIL_DOCK)) {
2694 s->SetDestTile(s->GetOrderStationLocation(st->index));
2699 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_STATION_DOCK]);
2702 #include "table/station_land.h"
2704 const DrawTileSprites *GetStationTileLayout(StationType st, byte gfx)
2706 return &_station_display_datas[st][gfx];
2710 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2711 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2712 * is set to the overlay to draw.
2713 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
2714 * @param[in,out] ground Groundsprite to draw.
2715 * @param[out] overlay_offset Overlay to draw.
2716 * @return true if overlay can be drawn.
2718 bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
2720 bool snow_desert;
2721 switch (*ground) {
2722 case SPR_RAIL_TRACK_X:
2723 case SPR_MONO_TRACK_X:
2724 case SPR_MGLV_TRACK_X:
2725 snow_desert = false;
2726 *overlay_offset = RTO_X;
2727 break;
2729 case SPR_RAIL_TRACK_Y:
2730 case SPR_MONO_TRACK_Y:
2731 case SPR_MGLV_TRACK_Y:
2732 snow_desert = false;
2733 *overlay_offset = RTO_Y;
2734 break;
2736 case SPR_RAIL_TRACK_X_SNOW:
2737 case SPR_MONO_TRACK_X_SNOW:
2738 case SPR_MGLV_TRACK_X_SNOW:
2739 snow_desert = true;
2740 *overlay_offset = RTO_X;
2741 break;
2743 case SPR_RAIL_TRACK_Y_SNOW:
2744 case SPR_MONO_TRACK_Y_SNOW:
2745 case SPR_MGLV_TRACK_Y_SNOW:
2746 snow_desert = true;
2747 *overlay_offset = RTO_Y;
2748 break;
2750 default:
2751 return false;
2754 if (ti != nullptr) {
2755 /* Decide snow/desert from tile */
2756 switch (_settings_game.game_creation.landscape) {
2757 case LT_ARCTIC:
2758 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
2759 break;
2761 case LT_TROPIC:
2762 snow_desert = GetTropicZone(ti->tile) == TROPICZONE_DESERT;
2763 break;
2765 default:
2766 break;
2770 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
2771 return true;
2774 static void DrawTile_Station(TileInfo *ti)
2776 const NewGRFSpriteLayout *layout = nullptr;
2777 DrawTileSprites tmp_rail_layout;
2778 const DrawTileSprites *t = nullptr;
2779 int32 total_offset;
2780 const RailtypeInfo *rti = nullptr;
2781 uint32 relocation = 0;
2782 uint32 ground_relocation = 0;
2783 BaseStation *st = nullptr;
2784 const StationSpec *statspec = nullptr;
2785 uint tile_layout = 0;
2787 if (HasStationRail(ti->tile)) {
2788 rti = GetRailTypeInfo(GetRailType(ti->tile));
2789 total_offset = rti->GetRailtypeSpriteOffset();
2791 if (IsCustomStationSpecIndex(ti->tile)) {
2792 /* look for customization */
2793 st = BaseStation::GetByTile(ti->tile);
2794 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
2796 if (statspec != nullptr) {
2797 tile_layout = GetStationGfx(ti->tile);
2799 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
2800 uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0, 0, statspec, st, ti->tile);
2801 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + GetRailStationAxis(ti->tile);
2804 /* Ensure the chosen tile layout is valid for this custom station */
2805 if (!statspec->renderdata.empty()) {
2806 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
2807 if (!layout->NeedsPreprocessing()) {
2808 t = layout;
2809 layout = nullptr;
2814 } else {
2815 total_offset = 0;
2818 StationGfx gfx = GetStationGfx(ti->tile);
2819 if (IsAirport(ti->tile)) {
2820 gfx = GetAirportGfx(ti->tile);
2821 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
2822 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
2823 if (ats->grf_prop.spritegroup[0] != nullptr && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), gfx, ats)) {
2824 return;
2826 /* No sprite group (or no valid one) found, meaning no graphics associated.
2827 * Use the substitute one instead */
2828 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
2829 gfx = ats->grf_prop.subst_id;
2831 switch (gfx) {
2832 case APT_RADAR_GRASS_FENCE_SW:
2833 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
2834 break;
2835 case APT_GRASS_FENCE_NE_FLAG:
2836 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
2837 break;
2838 case APT_RADAR_FENCE_SW:
2839 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
2840 break;
2841 case APT_RADAR_FENCE_NE:
2842 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
2843 break;
2844 case APT_GRASS_FENCE_NE_FLAG_2:
2845 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
2846 break;
2850 Owner owner = GetTileOwner(ti->tile);
2852 PaletteID palette;
2853 if (Company::IsValidID(owner)) {
2854 palette = COMPANY_SPRITE_COLOUR(owner);
2855 } else {
2856 /* Some stations are not owner by a company, namely oil rigs */
2857 palette = PALETTE_TO_GREY;
2860 if (layout == nullptr && (t == nullptr || t->seq == nullptr)) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
2862 /* don't show foundation for docks */
2863 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
2864 if (statspec != nullptr && HasBit(statspec->flags, SSF_CUSTOM_FOUNDATIONS)) {
2865 /* Station has custom foundations.
2866 * Check whether the foundation continues beyond the tile's upper sides. */
2867 uint edge_info = 0;
2868 int z;
2869 Slope slope = GetFoundationPixelSlope(ti->tile, &z);
2870 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
2871 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
2872 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, tile_layout, edge_info);
2873 if (image == 0) goto draw_default_foundation;
2875 if (HasBit(statspec->flags, SSF_EXTENDED_FOUNDATIONS)) {
2876 /* Station provides extended foundations. */
2878 static const uint8 foundation_parts[] = {
2879 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2880 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2881 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2882 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2885 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2886 } else {
2887 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2889 /* Each set bit represents one of the eight composite sprites to be drawn.
2890 * 'Invalid' entries will not drawn but are included for completeness. */
2891 static const uint8 composite_foundation_parts[] = {
2892 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2893 0x00, 0xD1, 0xE4, 0xE0,
2894 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2895 0xCA, 0xC9, 0xC4, 0xC0,
2896 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2897 0xD2, 0x91, 0xE4, 0xA0,
2898 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2899 0x4A, 0x09, 0x44
2902 uint8 parts = composite_foundation_parts[ti->tileh];
2904 /* If foundations continue beyond the tile's upper sides then
2905 * mask out the last two pieces. */
2906 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
2907 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
2909 if (parts == 0) {
2910 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2911 * correct offset for the childsprites.
2912 * So, draw the (completely empty) sprite of the default foundations. */
2913 goto draw_default_foundation;
2916 StartSpriteCombine();
2917 for (int i = 0; i < 8; i++) {
2918 if (HasBit(parts, i)) {
2919 AddSortableSpriteToDraw(image + i, PAL_NONE, ti->x, ti->y, 16, 16, 7, ti->z);
2922 EndSpriteCombine();
2925 OffsetGroundSprite(31, 1);
2926 ti->z += ApplyPixelFoundationToSlope(FOUNDATION_LEVELED, &ti->tileh);
2927 } else {
2928 draw_default_foundation:
2929 DrawFoundation(ti, FOUNDATION_LEVELED);
2933 if (IsBuoy(ti->tile)) {
2934 DrawWaterClassGround(ti);
2935 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
2936 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
2937 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
2938 if (ti->tileh == SLOPE_FLAT) {
2939 DrawWaterClassGround(ti);
2940 } else {
2941 assert(IsDock(ti->tile));
2942 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
2943 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WATER_CLASS_INVALID;
2944 if (wc == WATER_CLASS_SEA) {
2945 DrawShoreTile(ti->tileh);
2946 } else {
2947 DrawClearLandTile(ti, 3);
2950 } else {
2951 if (layout != nullptr) {
2952 /* Sprite layout which needs preprocessing */
2953 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
2954 uint32 var10_values = layout->PrepareLayout(total_offset, rti->fallback_railtype, 0, 0, separate_ground);
2955 for (uint8 var10 : SetBitIterator(var10_values)) {
2956 uint32 var10_relocation = GetCustomStationRelocation(statspec, st, ti->tile, var10);
2957 layout->ProcessRegisters(var10, var10_relocation, separate_ground);
2959 tmp_rail_layout.seq = layout->GetLayout(&tmp_rail_layout.ground);
2960 t = &tmp_rail_layout;
2961 total_offset = 0;
2962 } else if (statspec != nullptr) {
2963 /* Simple sprite layout */
2964 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
2965 if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
2966 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
2968 ground_relocation += rti->fallback_railtype;
2971 SpriteID image = t->ground.sprite;
2972 PaletteID pal = t->ground.pal;
2973 RailTrackOffset overlay_offset;
2974 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
2975 SpriteID ground = GetCustomRailSprite(rti, ti->tile, RTSG_GROUND);
2976 DrawGroundSprite(image, PAL_NONE);
2977 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
2979 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
2980 SpriteID overlay = GetCustomRailSprite(rti, ti->tile, RTSG_OVERLAY);
2981 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
2983 } else {
2984 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
2985 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
2986 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
2988 /* PBS debugging, draw reserved tracks darker */
2989 if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
2990 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
2991 DrawGroundSprite(GetRailStationAxis(ti->tile) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
2996 if (HasStationRail(ti->tile) && HasRailCatenaryDrawn(GetRailType(ti->tile))) DrawRailCatenary(ti);
2998 if (IsRoadStop(ti->tile)) {
2999 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3000 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3001 const RoadTypeInfo* road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3002 const RoadTypeInfo* tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3004 if (IsDriveThroughStopTile(ti->tile)) {
3005 Axis axis = GetRoadStopDir(ti->tile) == DIAGDIR_NE ? AXIS_X : AXIS_Y;
3006 uint sprite_offset = axis == AXIS_X ? 1 : 0;
3008 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3009 } else {
3010 /* Non-drivethrough road stops are only valid for roads. */
3011 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3013 if (road_rti->UsesOverlay()) {
3014 DiagDirection dir = GetRoadStopDir(ti->tile);
3015 SpriteID ground = GetCustomRoadSprite(road_rti, ti->tile, ROTSG_ROADSTOP);
3016 DrawGroundSprite(ground + dir, PAL_NONE);
3020 /* Draw road, tram catenary */
3021 DrawRoadCatenary(ti);
3024 if (IsRailWaypoint(ti->tile)) {
3025 /* Don't offset the waypoint graphics; they're always the same. */
3026 total_offset = 0;
3029 DrawRailTileSeq(ti, t, TO_BUILDINGS, total_offset, relocation, palette);
3032 void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3034 int32 total_offset = 0;
3035 PaletteID pal = COMPANY_SPRITE_COLOUR(_local_company);
3036 const DrawTileSprites *t = GetStationTileLayout(st, image);
3037 const RailtypeInfo *rti = nullptr;
3039 if (railtype != INVALID_RAILTYPE) {
3040 rti = GetRailTypeInfo(railtype);
3041 total_offset = rti->GetRailtypeSpriteOffset();
3044 SpriteID img = t->ground.sprite;
3045 RailTrackOffset overlay_offset;
3046 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3047 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
3048 DrawSprite(img, PAL_NONE, x, y);
3049 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3050 } else {
3051 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3054 if (roadtype != INVALID_ROADTYPE) {
3055 const RoadTypeInfo* rti = GetRoadTypeInfo(roadtype);
3056 if (image >= 4) {
3057 /* Drive-through stop */
3058 uint sprite_offset = 5 - image;
3060 /* Road underlay takes precedence over tram */
3061 if (rti->UsesOverlay()) {
3062 SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_GROUND);
3063 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3065 SpriteID overlay = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_OVERLAY);
3066 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3067 } else if (RoadTypeIsTram(roadtype)) {
3068 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3070 } else {
3071 /* Drive-in stop */
3072 if (RoadTypeIsRoad(roadtype) && rti->UsesOverlay()) {
3073 SpriteID ground = GetCustomRoadSprite(rti, INVALID_TILE, ROTSG_ROADSTOP);
3074 DrawSprite(ground + image, PAL_NONE, x, y);
3079 /* Default waypoint has no railtype specific sprites */
3080 DrawRailTileSeqInGUI(x, y, t, st == STATION_WAYPOINT ? 0 : total_offset, 0, pal);
3083 static int GetSlopePixelZ_Station(TileIndex tile, uint x, uint y)
3085 return GetTileMaxPixelZ(tile);
3088 static Foundation GetFoundation_Station(TileIndex tile, Slope tileh)
3090 return FlatteningFoundation(tileh);
3093 static void GetTileDesc_Station(TileIndex tile, TileDesc *td)
3095 td->owner[0] = GetTileOwner(tile);
3097 if (IsRoadStopTile(tile)) {
3098 RoadType road_rt = GetRoadTypeRoad(tile);
3099 RoadType tram_rt = GetRoadTypeTram(tile);
3100 Owner road_owner = INVALID_OWNER;
3101 Owner tram_owner = INVALID_OWNER;
3102 if (road_rt != INVALID_ROADTYPE) {
3103 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3104 td->roadtype = rti->strings.name;
3105 td->road_speed = rti->max_speed / 2;
3106 road_owner = GetRoadOwner(tile, RTT_ROAD);
3109 if (tram_rt != INVALID_ROADTYPE) {
3110 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3111 td->tramtype = rti->strings.name;
3112 td->tram_speed = rti->max_speed / 2;
3113 tram_owner = GetRoadOwner(tile, RTT_TRAM);
3116 if (IsDriveThroughStopTile(tile)) {
3117 /* Is there a mix of owners? */
3118 if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
3119 (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
3120 uint i = 1;
3121 if (road_owner != INVALID_OWNER) {
3122 td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3123 td->owner[i] = road_owner;
3124 i++;
3126 if (tram_owner != INVALID_OWNER) {
3127 td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3128 td->owner[i] = tram_owner;
3134 td->build_date = BaseStation::GetByTile(tile)->build_date;
3136 if (HasStationTileRail(tile)) {
3137 const StationSpec *spec = GetStationSpec(tile);
3139 if (spec != nullptr) {
3140 td->station_class = StationClass::Get(spec->cls_id)->name;
3141 td->station_name = spec->name;
3143 if (spec->grf_prop.grffile != nullptr) {
3144 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grffile->grfid);
3145 td->grf = gc->GetName();
3149 const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3150 td->rail_speed = rti->max_speed;
3151 td->railtype = rti->strings.name;
3154 if (IsAirport(tile)) {
3155 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3156 td->airport_class = AirportClass::Get(as->cls_id)->name;
3157 td->airport_name = as->name;
3159 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3160 td->airport_tile_name = ats->name;
3162 if (as->grf_prop.grffile != nullptr) {
3163 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grffile->grfid);
3164 td->grf = gc->GetName();
3165 } else if (ats->grf_prop.grffile != nullptr) {
3166 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grffile->grfid);
3167 td->grf = gc->GetName();
3171 StringID str;
3172 switch (GetStationType(tile)) {
3173 default: NOT_REACHED();
3174 case STATION_RAIL: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3175 case STATION_AIRPORT:
3176 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3177 break;
3178 case STATION_TRUCK: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3179 case STATION_BUS: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3180 case STATION_OILRIG: {
3181 const Industry *i = Station::GetByTile(tile)->industry;
3182 const IndustrySpec *is = GetIndustrySpec(i->type);
3183 td->owner[0] = i->owner;
3184 str = is->name;
3185 if (is->grf_prop.grffile != nullptr) td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
3186 break;
3188 case STATION_DOCK: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3189 case STATION_BUOY: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3190 case STATION_WAYPOINT: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3192 td->str = str;
3196 static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
3198 TrackBits trackbits = TRACK_BIT_NONE;
3200 switch (mode) {
3201 case TRANSPORT_RAIL:
3202 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3203 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3205 break;
3207 case TRANSPORT_WATER:
3208 /* buoy is coded as a station, it is always on open water */
3209 if (IsBuoy(tile)) {
3210 trackbits = TRACK_BIT_ALL;
3211 /* remove tracks that connect NE map edge */
3212 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3213 /* remove tracks that connect NW map edge */
3214 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3216 break;
3218 case TRANSPORT_ROAD:
3219 if (IsRoadStop(tile)) {
3220 RoadTramType rtt = (RoadTramType)sub_mode;
3221 if (!HasTileRoadType(tile, rtt)) break;
3223 DiagDirection dir = GetRoadStopDir(tile);
3224 Axis axis = DiagDirToAxis(dir);
3226 if (side != INVALID_DIAGDIR) {
3227 if (axis != DiagDirToAxis(side) || (IsStandardRoadStopTile(tile) && dir != side)) break;
3230 trackbits = AxisToTrackBits(axis);
3232 break;
3234 default:
3235 break;
3238 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE);
3242 static void TileLoop_Station(TileIndex tile)
3244 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3245 * hardcoded.....not good */
3246 switch (GetStationType(tile)) {
3247 case STATION_AIRPORT:
3248 AirportTileAnimationTrigger(Station::GetByTile(tile), tile, AAT_TILELOOP);
3249 break;
3251 case STATION_DOCK:
3252 if (!IsTileFlat(tile)) break; // only handle water part
3253 FALLTHROUGH;
3255 case STATION_OILRIG: //(station part)
3256 case STATION_BUOY:
3257 TileLoop_Water(tile);
3258 break;
3260 default: break;
3265 static void AnimateTile_Station(TileIndex tile)
3267 if (HasStationRail(tile)) {
3268 AnimateStationTile(tile);
3269 return;
3272 if (IsAirport(tile)) {
3273 AnimateAirportTile(tile);
3278 static bool ClickTile_Station(TileIndex tile)
3280 const BaseStation *bst = BaseStation::GetByTile(tile);
3282 if (bst->facilities & FACIL_WAYPOINT) {
3283 ShowWaypointWindow(Waypoint::From(bst));
3284 } else if (IsHangar(tile)) {
3285 const Station *st = Station::From(bst);
3286 ShowDepotWindow(st->airport.GetHangarTile(st->airport.GetHangarNum(tile)), VEH_AIRCRAFT);
3287 } else {
3288 ShowStationViewWindow(bst->index);
3290 return true;
3293 static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
3295 if (v->type == VEH_TRAIN) {
3296 StationID station_id = GetStationIndex(tile);
3297 if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
3298 if (!IsRailStation(tile) || !v->IsFrontEngine()) return VETSB_CONTINUE;
3300 int station_ahead;
3301 int station_length;
3302 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3304 /* Stop whenever that amount of station ahead + the distance from the
3305 * begin of the platform to the stop location is longer than the length
3306 * of the platform. Station ahead 'includes' the current tile where the
3307 * vehicle is on, so we need to subtract that. */
3308 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return VETSB_CONTINUE;
3310 DiagDirection dir = DirToDiagDir(v->direction);
3312 x &= 0xF;
3313 y &= 0xF;
3315 if (DiagDirToAxis(dir) != AXIS_X) Swap(x, y);
3316 if (y == TILE_SIZE / 2) {
3317 if (dir != DIAGDIR_SE && dir != DIAGDIR_SW) x = TILE_SIZE - 1 - x;
3318 stop &= TILE_SIZE - 1;
3320 if (x == stop) {
3321 return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
3322 } else if (x < stop) {
3323 v->vehstatus |= VS_TRAIN_SLOWING;
3324 uint16 spd = std::max(0, (stop - x) * 20 - 15);
3325 if (spd < v->cur_speed) v->cur_speed = spd;
3328 } else if (v->type == VEH_ROAD) {
3329 RoadVehicle *rv = RoadVehicle::From(v);
3330 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3331 if (IsRoadStop(tile) && rv->IsFrontEngine()) {
3332 /* Attempt to allocate a parking bay in a road stop */
3333 return RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv) ? VETSB_CONTINUE : VETSB_CANNOT_ENTER;
3338 return VETSB_CONTINUE;
3342 * Run the watched cargo callback for all houses in the catchment area.
3343 * @param st Station.
3345 void TriggerWatchedCargoCallbacks(Station *st)
3347 /* Collect cargoes accepted since the last big tick. */
3348 CargoTypes cargoes = 0;
3349 for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
3350 if (HasBit(st->goods[cid].status, GoodsEntry::GES_ACCEPTED_BIGTICK)) SetBit(cargoes, cid);
3353 /* Anything to do? */
3354 if (cargoes == 0) return;
3356 /* Loop over all houses in the catchment. */
3357 BitmapTileIterator it(st->catchment_tiles);
3358 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3359 if (IsTileType(tile, MP_HOUSE)) {
3360 WatchedCargoCallback(tile, cargoes);
3366 * This function is called for each station once every 250 ticks.
3367 * Not all stations will get the tick at the same time.
3368 * @param st the station receiving the tick.
3369 * @return true if the station is still valid (wasn't deleted)
3371 static bool StationHandleBigTick(BaseStation *st)
3373 if (!st->IsInUse()) {
3374 if (++st->delete_ctr >= 8) delete st;
3375 return false;
3378 if (Station::IsExpected(st)) {
3379 TriggerWatchedCargoCallbacks(Station::From(st));
3381 for (CargoID i = 0; i < NUM_CARGO; i++) {
3382 ClrBit(Station::From(st)->goods[i].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
3387 if ((st->facilities & FACIL_WAYPOINT) == 0) UpdateStationAcceptance(Station::From(st), true);
3389 return true;
3392 static inline void byte_inc_sat(byte *p)
3394 byte b = *p + 1;
3395 if (b != 0) *p = b;
3399 * Truncate the cargo by a specific amount.
3400 * @param cs The type of cargo to perform the truncation for.
3401 * @param ge The goods entry, of the station, to truncate.
3402 * @param amount The amount to truncate the cargo by.
3404 static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3406 /* If truncating also punish the source stations' ratings to
3407 * decrease the flow of incoming cargo. */
3409 StationCargoAmountMap waiting_per_source;
3410 ge->cargo.Truncate(amount, &waiting_per_source);
3411 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3412 Station *source_station = Station::GetIfValid(i->first);
3413 if (source_station == nullptr) continue;
3415 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3416 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3420 static void UpdateStationRating(Station *st)
3422 bool waiting_changed = false;
3424 byte_inc_sat(&st->time_since_load);
3425 byte_inc_sat(&st->time_since_unload);
3427 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3428 GoodsEntry *ge = &st->goods[cs->Index()];
3429 /* Slowly increase the rating back to its original level in the case we
3430 * didn't deliver cargo yet to this station. This happens when a bribe
3431 * failed while you didn't moved that cargo yet to a station. */
3432 if (!ge->HasRating() && ge->rating < INITIAL_STATION_RATING) {
3433 ge->rating++;
3436 /* Only change the rating if we are moving this cargo */
3437 if (ge->HasRating()) {
3438 byte_inc_sat(&ge->time_since_pickup);
3439 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3440 ClrBit(ge->status, GoodsEntry::GES_RATING);
3441 ge->last_speed = 0;
3442 TruncateCargo(cs, ge);
3443 waiting_changed = true;
3444 continue;
3447 bool skip = false;
3448 int rating = 0;
3449 uint waiting = ge->cargo.AvailableCount();
3451 /* num_dests is at least 1 if there is any cargo as
3452 * INVALID_STATION is also a destination.
3454 uint num_dests = (uint)ge->cargo.Packets()->MapSize();
3456 /* Average amount of cargo per next hop, but prefer solitary stations
3457 * with only one or two next hops. They are allowed to have more
3458 * cargo waiting per next hop.
3459 * With manual cargo distribution waiting_avg = waiting / 2 as then
3460 * INVALID_STATION is the only destination.
3462 uint waiting_avg = waiting / (num_dests + 1);
3464 if (HasBit(cs->callback_mask, CBM_CARGO_STATION_RATING_CALC)) {
3465 /* Perform custom station rating. If it succeeds the speed, days in transit and
3466 * waiting cargo ratings must not be executed. */
3468 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3469 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
3471 uint32 var18 = std::min<uint>(ge->time_since_pickup, 0xFFu)
3472 | (std::min<uint>(ge->max_waiting_cargo, 0xFFFFu) << 8)
3473 | (std::min<uint>(last_speed, 0xFFu) << 24);
3474 /* Convert to the 'old' vehicle types */
3475 uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
3476 uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
3477 if (callback != CALLBACK_FAILED) {
3478 skip = true;
3479 rating = GB(callback, 0, 14);
3481 /* Simulate a 15 bit signed value */
3482 if (HasBit(callback, 14)) rating -= 0x4000;
3486 if (!skip) {
3487 int b = ge->last_speed - 85;
3488 if (b >= 0) rating += b >> 2;
3490 byte waittime = ge->time_since_pickup;
3491 if (st->last_vehicle_type == VEH_SHIP) waittime >>= 2;
3492 if (waittime <= 21) rating += 25;
3493 if (waittime <= 12) rating += 25;
3494 if (waittime <= 6) rating += 45;
3495 if (waittime <= 3) rating += 35;
3497 rating -= 90;
3498 if (ge->max_waiting_cargo <= 1500) rating += 55;
3499 if (ge->max_waiting_cargo <= 1000) rating += 35;
3500 if (ge->max_waiting_cargo <= 600) rating += 10;
3501 if (ge->max_waiting_cargo <= 300) rating += 20;
3502 if (ge->max_waiting_cargo <= 100) rating += 10;
3505 if (Company::IsValidID(st->owner) && HasBit(st->town->statues, st->owner)) rating += 26;
3507 byte age = ge->last_age;
3508 if (age < 3) rating += 10;
3509 if (age < 2) rating += 10;
3510 if (age < 1) rating += 13;
3513 int or_ = ge->rating; // old rating
3515 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3516 ge->rating = rating = or_ + Clamp(Clamp(rating, 0, 255) - or_, -2, 2);
3518 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3519 * remove some random amount of goods from the station */
3520 if (rating <= 64 && waiting_avg >= 100) {
3521 int dec = Random() & 0x1F;
3522 if (waiting_avg < 200) dec &= 7;
3523 waiting -= (dec + 1) * num_dests;
3524 waiting_changed = true;
3527 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3528 if (rating <= 127 && waiting != 0) {
3529 uint32 r = Random();
3530 if (rating <= (int)GB(r, 0, 7)) {
3531 /* Need to have int, otherwise it will just overflow etc. */
3532 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) - 1) * num_dests), 0);
3533 waiting_changed = true;
3537 /* At some point we really must cap the cargo. Previously this
3538 * was a strict 4095, but now we'll have a less strict, but
3539 * increasingly aggressive truncation of the amount of cargo. */
3540 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
3541 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
3542 static const uint MAX_WAITING_CARGO = 1 << 15;
3544 if (waiting > WAITING_CARGO_THRESHOLD) {
3545 uint difference = waiting - WAITING_CARGO_THRESHOLD;
3546 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
3548 waiting = std::min(waiting, MAX_WAITING_CARGO);
3549 waiting_changed = true;
3552 /* We can't truncate cargo that's already reserved for loading.
3553 * Thus StoredCount() here. */
3554 if (waiting_changed && waiting < ge->cargo.AvailableCount()) {
3555 /* Feed back the exact own waiting cargo at this station for the
3556 * next rating calculation. */
3557 ge->max_waiting_cargo = 0;
3559 TruncateCargo(cs, ge, ge->cargo.AvailableCount() - waiting);
3560 } else {
3561 /* If the average number per next hop is low, be more forgiving. */
3562 ge->max_waiting_cargo = waiting_avg;
3568 StationID index = st->index;
3569 if (waiting_changed) {
3570 SetWindowDirty(WC_STATION_VIEW, index); // update whole window
3571 } else {
3572 SetWindowWidgetDirty(WC_STATION_VIEW, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
3577 * Reroute cargo of type c at station st or in any vehicles unloading there.
3578 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3579 * @param st Station to be rerouted at.
3580 * @param c Type of cargo.
3581 * @param avoid Original next hop of cargo, avoid this.
3582 * @param avoid2 Another station to be avoided when rerouting.
3584 void RerouteCargo(Station *st, CargoID c, StationID avoid, StationID avoid2)
3586 GoodsEntry &ge = st->goods[c];
3588 /* Reroute cargo in station. */
3589 ge.cargo.Reroute(UINT_MAX, &ge.cargo, avoid, avoid2, &ge);
3591 /* Reroute cargo staged to be transferred. */
3592 for (std::list<Vehicle *>::iterator it(st->loading_vehicles.begin()); it != st->loading_vehicles.end(); ++it) {
3593 for (Vehicle *v = *it; v != nullptr; v = v->Next()) {
3594 if (v->cargo_type != c) continue;
3595 v->cargo.Reroute(UINT_MAX, &v->cargo, avoid, avoid2, &ge);
3601 * Check all next hops of cargo packets in this station for existence of a
3602 * a valid link they may use to travel on. Reroute any cargo not having a valid
3603 * link and remove timed out links found like this from the linkgraph. We're
3604 * not all links here as that is expensive and useless. A link no one is using
3605 * doesn't hurt either.
3606 * @param from Station to check.
3608 void DeleteStaleLinks(Station *from)
3610 for (CargoID c = 0; c < NUM_CARGO; ++c) {
3611 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(c) != DT_MANUAL);
3612 GoodsEntry &ge = from->goods[c];
3613 LinkGraph *lg = LinkGraph::GetIfValid(ge.link_graph);
3614 if (lg == nullptr) continue;
3615 Node node = (*lg)[ge.node];
3616 for (EdgeIterator it(node.Begin()); it != node.End();) {
3617 Edge edge = it->second;
3618 Station *to = Station::Get((*lg)[it->first].Station());
3619 assert(to->goods[c].node == it->first);
3620 ++it; // Do that before removing the edge. Anything else may crash.
3621 assert(_date >= edge.LastUpdate());
3622 uint timeout = LinkGraph::MIN_TIMEOUT_DISTANCE + (DistanceManhattan(from->xy, to->xy) >> 3);
3623 if ((uint)(_date - edge.LastUpdate()) > timeout) {
3624 bool updated = false;
3626 if (auto_distributed) {
3627 /* Have all vehicles refresh their next hops before deciding to
3628 * remove the node. */
3629 std::vector<Vehicle *> vehicles;
3630 for (OrderList *l : OrderList::Iterate()) {
3631 bool found_from = false;
3632 bool found_to = false;
3633 for (Order *order = l->GetFirstOrder(); order != nullptr; order = order->next) {
3634 if (!order->IsType(OT_GOTO_STATION) && !order->IsType(OT_IMPLICIT)) continue;
3635 if (order->GetDestination() == from->index) {
3636 found_from = true;
3637 if (found_to) break;
3638 } else if (order->GetDestination() == to->index) {
3639 found_to = true;
3640 if (found_from) break;
3643 if (!found_to || !found_from) continue;
3644 vehicles.push_back(l->GetFirstSharedVehicle());
3647 auto iter = vehicles.begin();
3648 while (iter != vehicles.end()) {
3649 Vehicle *v = *iter;
3650 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
3651 if (!v->IsStoppedInDepot() || static_cast<uint>(_date - v->date_of_last_service) <=
3652 LinkGraph::STALE_LINK_DEPOT_TIMEOUT) {
3653 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
3655 if (edge.LastUpdate() == _date) {
3656 updated = true;
3657 break;
3660 Vehicle *next_shared = v->NextShared();
3661 if (next_shared) {
3662 *iter = next_shared;
3663 ++iter;
3664 } else {
3665 iter = vehicles.erase(iter);
3668 if (iter == vehicles.end()) iter = vehicles.begin();
3672 if (!updated) {
3673 /* If it's still considered dead remove it. */
3674 node.RemoveEdge(to->goods[c].node);
3675 ge.flows.DeleteFlows(to->index);
3676 RerouteCargo(from, c, to->index, from->index);
3678 } else if (edge.LastUnrestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastUnrestrictedUpdate()) > timeout) {
3679 edge.Restrict();
3680 ge.flows.RestrictFlows(to->index);
3681 RerouteCargo(from, c, to->index, from->index);
3682 } else if (edge.LastRestrictedUpdate() != INVALID_DATE && (uint)(_date - edge.LastRestrictedUpdate()) > timeout) {
3683 edge.Release();
3686 assert(_date >= lg->LastCompression());
3687 if ((uint)(_date - lg->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL) {
3688 lg->Compress();
3694 * Increase capacity for a link stat given by station cargo and next hop.
3695 * @param st Station to get the link stats from.
3696 * @param cargo Cargo to increase stat for.
3697 * @param next_station_id Station the consist will be travelling to next.
3698 * @param capacity Capacity to add to link stat.
3699 * @param usage Usage to add to link stat.
3700 * @param mode Update mode to be applied.
3702 void IncreaseStats(Station *st, CargoID cargo, StationID next_station_id, uint capacity, uint usage, uint32 time, EdgeUpdateMode mode)
3704 GoodsEntry &ge1 = st->goods[cargo];
3705 Station *st2 = Station::Get(next_station_id);
3706 GoodsEntry &ge2 = st2->goods[cargo];
3707 LinkGraph *lg = nullptr;
3708 if (ge1.link_graph == INVALID_LINK_GRAPH) {
3709 if (ge2.link_graph == INVALID_LINK_GRAPH) {
3710 if (LinkGraph::CanAllocateItem()) {
3711 lg = new LinkGraph(cargo);
3712 LinkGraphSchedule::instance.Queue(lg);
3713 ge2.link_graph = lg->index;
3714 ge2.node = lg->AddNode(st2);
3715 } else {
3716 Debug(misc, 0, "Can't allocate link graph");
3718 } else {
3719 lg = LinkGraph::Get(ge2.link_graph);
3721 if (lg) {
3722 ge1.link_graph = lg->index;
3723 ge1.node = lg->AddNode(st);
3725 } else if (ge2.link_graph == INVALID_LINK_GRAPH) {
3726 lg = LinkGraph::Get(ge1.link_graph);
3727 ge2.link_graph = lg->index;
3728 ge2.node = lg->AddNode(st2);
3729 } else {
3730 lg = LinkGraph::Get(ge1.link_graph);
3731 if (ge1.link_graph != ge2.link_graph) {
3732 LinkGraph *lg2 = LinkGraph::Get(ge2.link_graph);
3733 if (lg->Size() < lg2->Size()) {
3734 LinkGraphSchedule::instance.Unqueue(lg);
3735 lg2->Merge(lg); // Updates GoodsEntries of lg
3736 lg = lg2;
3737 } else {
3738 LinkGraphSchedule::instance.Unqueue(lg2);
3739 lg->Merge(lg2); // Updates GoodsEntries of lg2
3743 if (lg != nullptr) {
3744 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, mode);
3749 * Increase capacity for all link stats associated with vehicles in the given consist.
3750 * @param st Station to get the link stats from.
3751 * @param front First vehicle in the consist.
3752 * @param next_station_id Station the consist will be travelling to next.
3754 void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32 time)
3756 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
3757 if (v->refit_cap > 0) {
3758 /* The cargo count can indeed be higher than the refit_cap if
3759 * wagons have been auto-replaced and subsequently auto-
3760 * refitted to a higher capacity. The cargo gets redistributed
3761 * among the wagons in that case.
3762 * As usage is not such an important figure anyway we just
3763 * ignore the additional cargo then.*/
3764 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
3765 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EUM_INCREASE);
3770 /* called for every station each tick */
3771 static void StationHandleSmallTick(BaseStation *st)
3773 if ((st->facilities & FACIL_WAYPOINT) != 0 || !st->IsInUse()) return;
3775 byte b = st->delete_ctr + 1;
3776 if (b >= STATION_RATING_TICKS) b = 0;
3777 st->delete_ctr = b;
3779 if (b == 0) UpdateStationRating(Station::From(st));
3782 void OnTick_Station()
3784 if (_game_mode == GM_EDITOR) return;
3786 for (BaseStation *st : BaseStation::Iterate()) {
3787 StationHandleSmallTick(st);
3789 /* Clean up the link graph about once a week. */
3790 if (Station::IsExpected(st) && (_tick_counter + st->index) % STATION_LINKGRAPH_TICKS == 0) {
3791 DeleteStaleLinks(Station::From(st));
3794 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3795 * Station index is included so that triggers are not all done
3796 * at the same time. */
3797 if ((_tick_counter + st->index) % STATION_ACCEPTANCE_TICKS == 0) {
3798 /* Stop processing this station if it was deleted */
3799 if (!StationHandleBigTick(st)) continue;
3800 TriggerStationAnimation(st, st->xy, SAT_250_TICKS);
3801 if (Station::IsExpected(st)) AirportAnimationTrigger(Station::From(st), AAT_STATION_250_TICKS);
3806 /** Monthly loop for stations. */
3807 void StationMonthlyLoop()
3809 for (Station *st : Station::Iterate()) {
3810 for (CargoID i = 0; i < NUM_CARGO; i++) {
3811 GoodsEntry *ge = &st->goods[i];
3812 SB(ge->status, GoodsEntry::GES_LAST_MONTH, 1, GB(ge->status, GoodsEntry::GES_CURRENT_MONTH, 1));
3813 ClrBit(ge->status, GoodsEntry::GES_CURRENT_MONTH);
3819 void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
3821 ForAllStationsRadius(tile, radius, [&](Station *st) {
3822 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
3823 for (CargoID i = 0; i < NUM_CARGO; i++) {
3824 GoodsEntry *ge = &st->goods[i];
3826 if (ge->status != 0) {
3827 ge->rating = Clamp(ge->rating + amount, 0, 255);
3834 static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceType source_type, SourceID source_id)
3836 /* We can't allocate a CargoPacket? Then don't do anything
3837 * at all; i.e. just discard the incoming cargo. */
3838 if (!CargoPacket::CanAllocateItem()) return 0;
3840 GoodsEntry &ge = st->goods[type];
3841 amount += ge.amount_fract;
3842 ge.amount_fract = GB(amount, 0, 8);
3844 amount >>= 8;
3845 /* No new "real" cargo item yet. */
3846 if (amount == 0) return 0;
3848 StationID next = ge.GetVia(st->index);
3849 ge.cargo.Append(new CargoPacket(st->index, st->xy, amount, source_type, source_id), next);
3850 LinkGraph *lg = nullptr;
3851 if (ge.link_graph == INVALID_LINK_GRAPH) {
3852 if (LinkGraph::CanAllocateItem()) {
3853 lg = new LinkGraph(type);
3854 LinkGraphSchedule::instance.Queue(lg);
3855 ge.link_graph = lg->index;
3856 ge.node = lg->AddNode(st);
3857 } else {
3858 Debug(misc, 0, "Can't allocate link graph");
3860 } else {
3861 lg = LinkGraph::Get(ge.link_graph);
3863 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
3865 if (!ge.HasRating()) {
3866 InvalidateWindowData(WC_STATION_LIST, st->index);
3867 SetBit(ge.status, GoodsEntry::GES_RATING);
3870 TriggerStationRandomisation(st, st->xy, SRT_NEW_CARGO, type);
3871 TriggerStationAnimation(st, st->xy, SAT_NEW_CARGO, type);
3872 AirportAnimationTrigger(st, AAT_STATION_NEW_CARGO, type);
3874 SetWindowDirty(WC_STATION_VIEW, st->index);
3875 st->MarkTilesDirty(true);
3876 return amount;
3879 static bool IsUniqueStationName(const std::string &name)
3881 for (const Station *st : Station::Iterate()) {
3882 if (!st->name.empty() && st->name == name) return false;
3885 return true;
3889 * Rename a station
3890 * @param flags operation to perform
3891 * @param station_id station ID that is to be renamed
3892 * @param text the new name or an empty string when resetting to the default
3893 * @return the cost of this operation or an error
3895 CommandCost CmdRenameStation(DoCommandFlag flags, StationID station_id, const std::string &text)
3897 Station *st = Station::GetIfValid(station_id);
3898 if (st == nullptr) return CMD_ERROR;
3900 CommandCost ret = CheckOwnership(st->owner);
3901 if (ret.Failed()) return ret;
3903 bool reset = text.empty();
3905 if (!reset) {
3906 if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR;
3907 if (!IsUniqueStationName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
3910 if (flags & DC_EXEC) {
3911 st->cached_name.clear();
3912 if (reset) {
3913 st->name.clear();
3914 } else {
3915 st->name = text;
3918 st->UpdateVirtCoord();
3919 InvalidateWindowData(WC_STATION_LIST, st->owner, 1);
3922 return CommandCost();
3925 static void AddNearbyStationsByCatchment(TileIndex tile, StationList *stations, StationList &nearby)
3927 for (Station *st : nearby) {
3928 if (st->TileIsInCatchment(tile)) stations->insert(st);
3933 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
3934 * @return pointer to a StationList containing all stations found
3936 const StationList *StationFinder::GetStations()
3938 if (this->tile != INVALID_TILE) {
3939 if (IsTileType(this->tile, MP_HOUSE)) {
3940 /* Town nearby stations need to be filtered per tile. */
3941 assert(this->w == 1 && this->h == 1);
3942 AddNearbyStationsByCatchment(this->tile, &this->stations, Town::GetByTile(this->tile)->stations_near);
3943 } else {
3944 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex tile) {
3945 this->stations.insert(st);
3946 return true;
3949 this->tile = INVALID_TILE;
3951 return &this->stations;
3955 static bool CanMoveGoodsToStation(const Station *st, CargoID type)
3957 /* Is the station reserved exclusively for somebody else? */
3958 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
3960 /* Lowest possible rating, better not to give cargo anymore. */
3961 if (st->goods[type].rating == 0) return false;
3963 /* Selectively servicing stations, and not this one. */
3964 if (_settings_game.order.selectgoods && !st->goods[type].HasVehicleEverTriedLoading()) return false;
3966 if (IsCargoInClass(type, CC_PASSENGERS)) {
3967 /* Passengers are never served by just a truck stop. */
3968 if (st->facilities == FACIL_TRUCK_STOP) return false;
3969 } else {
3970 /* Non-passengers are never served by just a bus stop. */
3971 if (st->facilities == FACIL_BUS_STOP) return false;
3973 return true;
3976 uint MoveGoodsToStation(CargoID type, uint amount, SourceType source_type, SourceID source_id, const StationList *all_stations, Owner exclusivity)
3978 /* Return if nothing to do. Also the rounding below fails for 0. */
3979 if (all_stations->empty()) return 0;
3980 if (amount == 0) return 0;
3982 Station *first_station = nullptr;
3983 typedef std::pair<Station *, uint> StationInfo;
3984 std::vector<StationInfo> used_stations;
3986 for (Station *st : *all_stations) {
3987 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
3988 if (!CanMoveGoodsToStation(st, type)) continue;
3990 /* Avoid allocating a vector if there is only one station to significantly
3991 * improve performance in this common case. */
3992 if (first_station == nullptr) {
3993 first_station = st;
3994 continue;
3996 if (used_stations.empty()) {
3997 used_stations.reserve(2);
3998 used_stations.emplace_back(std::make_pair(first_station, 0));
4000 used_stations.emplace_back(std::make_pair(st, 0));
4003 /* no stations around at all? */
4004 if (first_station == nullptr) return 0;
4006 if (used_stations.empty()) {
4007 /* only one station around */
4008 amount *= first_station->goods[type].rating + 1;
4009 return UpdateStationWaiting(first_station, type, amount, source_type, source_id);
4012 uint company_best[OWNER_NONE + 1] = {}; // best rating for each company, including OWNER_NONE
4013 uint company_sum[OWNER_NONE + 1] = {}; // sum of ratings for each company
4014 uint best_rating = 0;
4015 uint best_sum = 0; // sum of best ratings for each company
4017 for (auto &p : used_stations) {
4018 auto owner = p.first->owner;
4019 auto rating = p.first->goods[type].rating;
4020 if (rating > company_best[owner]) {
4021 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4022 company_best[owner] = rating;
4023 if (rating > best_rating) best_rating = rating;
4025 company_sum[owner] += rating;
4028 /* From now we'll calculate with fractional cargo amounts.
4029 * First determine how much cargo we really have. */
4030 amount *= best_rating + 1;
4032 uint moving = 0;
4033 for (auto &p : used_stations) {
4034 uint owner = p.first->owner;
4035 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4036 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4037 p.second = amount * company_best[owner] * p.first->goods[type].rating / best_sum / company_sum[owner];
4038 moving += p.second;
4041 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4042 if (amount > moving) {
4043 std::stable_sort(used_stations.begin(), used_stations.end(), [type](const StationInfo &a, const StationInfo &b) {
4044 return b.first->goods[type].rating < a.first->goods[type].rating;
4047 assert(amount - moving <= used_stations.size());
4048 for (uint i = 0; i < amount - moving; i++) {
4049 used_stations[i].second++;
4053 uint moved = 0;
4054 for (auto &p : used_stations) {
4055 moved += UpdateStationWaiting(p.first, type, p.second, source_type, source_id);
4058 return moved;
4061 void UpdateStationDockingTiles(Station *st)
4063 st->docking_station.Clear();
4065 /* For neutral stations, start with the industry area instead of dock area */
4066 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4068 if (area->tile == INVALID_TILE) return;
4070 int x = TileX(area->tile);
4071 int y = TileY(area->tile);
4073 /* Expand the area by a tile on each side while
4074 * making sure that we remain inside the map. */
4075 int x2 = std::min<int>(x + area->w + 1, MapSizeX());
4076 int x1 = std::max<int>(x - 1, 0);
4078 int y2 = std::min<int>(y + area->h + 1, MapSizeY());
4079 int y1 = std::max<int>(y - 1, 0);
4081 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4082 for (TileIndex tile : ta) {
4083 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4087 void BuildOilRig(TileIndex tile)
4089 if (!Station::CanAllocateItem()) {
4090 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4091 return;
4094 Station *st = new Station(tile);
4095 _station_kdtree.Insert(st->index);
4096 st->town = ClosestTownFromTile(tile, UINT_MAX);
4098 st->string_id = GenerateStationName(st, tile, STATIONNAMING_OILRIG);
4100 assert(IsTileType(tile, MP_INDUSTRY));
4101 /* Mark industry as associated both ways */
4102 st->industry = Industry::GetByTile(tile);
4103 st->industry->neutral_station = st;
4104 DeleteAnimatedTile(tile);
4105 MakeOilrig(tile, st->index, GetWaterClass(tile));
4107 st->owner = OWNER_NONE;
4108 st->airport.type = AT_OILRIG;
4109 st->airport.Add(tile);
4110 st->ship_station.Add(tile);
4111 st->facilities = FACIL_AIRPORT | FACIL_DOCK;
4112 st->build_date = _date;
4113 UpdateStationDockingTiles(st);
4115 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4117 st->UpdateVirtCoord();
4118 st->RecomputeCatchment();
4119 UpdateStationAcceptance(st, false);
4122 void DeleteOilRig(TileIndex tile)
4124 Station *st = Station::GetByTile(tile);
4126 MakeWaterKeepingClass(tile, OWNER_NONE);
4128 /* The oil rig station is not supposed to be shared with anything else */
4129 assert(st->facilities == (FACIL_AIRPORT | FACIL_DOCK) && st->airport.type == AT_OILRIG);
4130 if (st->industry != nullptr && st->industry->neutral_station == st) {
4131 /* Don't leave dangling neutral station pointer */
4132 st->industry->neutral_station = nullptr;
4134 delete st;
4137 static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4139 if (IsRoadStopTile(tile)) {
4140 for (RoadTramType rtt : _roadtramtypes) {
4141 /* Update all roadtypes, no matter if they are present */
4142 if (GetRoadOwner(tile, rtt) == old_owner) {
4143 RoadType rt = GetRoadType(tile, rtt);
4144 if (rt != INVALID_ROADTYPE) {
4145 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4146 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4147 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4149 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4154 if (!IsTileOwner(tile, old_owner)) return;
4156 if (new_owner != INVALID_OWNER) {
4157 /* Update company infrastructure counts. Only do it here
4158 * if the new owner is valid as otherwise the clear
4159 * command will do it for us. No need to dirty windows
4160 * here, we'll redraw the whole screen anyway.*/
4161 Company *old_company = Company::Get(old_owner);
4162 Company *new_company = Company::Get(new_owner);
4164 /* Update counts for underlying infrastructure. */
4165 switch (GetStationType(tile)) {
4166 case STATION_RAIL:
4167 case STATION_WAYPOINT:
4168 if (!IsStationTileBlocked(tile)) {
4169 old_company->infrastructure.rail[GetRailType(tile)]--;
4170 new_company->infrastructure.rail[GetRailType(tile)]++;
4172 break;
4174 case STATION_BUS:
4175 case STATION_TRUCK:
4176 /* Road stops were already handled above. */
4177 break;
4179 case STATION_BUOY:
4180 case STATION_DOCK:
4181 if (GetWaterClass(tile) == WATER_CLASS_CANAL) {
4182 old_company->infrastructure.water--;
4183 new_company->infrastructure.water++;
4185 break;
4187 default:
4188 break;
4191 /* Update station tile count. */
4192 if (!IsBuoy(tile) && !IsAirport(tile)) {
4193 old_company->infrastructure.station--;
4194 new_company->infrastructure.station++;
4197 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4198 SetTileOwner(tile, new_owner);
4199 InvalidateWindowClassesData(WC_STATION_LIST, 0);
4200 } else {
4201 if (IsDriveThroughStopTile(tile)) {
4202 /* Remove the drive-through road stop */
4203 Command<CMD_REMOVE_ROAD_STOP>::Do(DC_EXEC | DC_BANKRUPT, tile, 1, 1, (GetStationType(tile) == STATION_TRUCK) ? ROADSTOP_TRUCK : ROADSTOP_BUS, false);
4204 assert(IsTileType(tile, MP_ROAD));
4205 /* Change owner of tile and all roadtypes */
4206 ChangeTileOwner(tile, old_owner, new_owner);
4207 } else {
4208 Command<CMD_LANDSCAPE_CLEAR>::Do(DC_EXEC | DC_BANKRUPT, tile);
4209 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4210 * Update owner of buoy if it was not removed (was in orders).
4211 * Do not update when owned by OWNER_WATER (sea and rivers). */
4212 if ((IsTileType(tile, MP_WATER) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4218 * Check if a drive-through road stop tile can be cleared.
4219 * Road stops built on town-owned roads check the conditions
4220 * that would allow clearing of the original road.
4221 * @param tile road stop tile to check
4222 * @param flags command flags
4223 * @return true if the road can be cleared
4225 static bool CanRemoveRoadWithStop(TileIndex tile, DoCommandFlag flags)
4227 /* Yeah... water can always remove stops, right? */
4228 if (_current_company == OWNER_WATER) return true;
4230 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4231 Owner tram_owner = GetRoadOwner(tile, RTT_TRAM);
4232 if (tram_owner != OWNER_NONE && CheckOwnership(tram_owner).Failed()) return false;
4234 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4235 Owner road_owner = GetRoadOwner(tile, RTT_ROAD);
4236 if (road_owner != OWNER_TOWN) {
4237 if (road_owner != OWNER_NONE && CheckOwnership(road_owner).Failed()) return false;
4238 } else {
4239 if (CheckAllowRemoveRoad(tile, GetAnyRoadBits(tile, RTT_ROAD), OWNER_TOWN, RTT_ROAD, flags).Failed()) return false;
4243 return true;
4247 * Clear a single tile of a station.
4248 * @param tile The tile to clear.
4249 * @param flags The DoCommand flags related to the "command".
4250 * @return The cost, or error of clearing.
4252 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags)
4254 if (flags & DC_AUTO) {
4255 switch (GetStationType(tile)) {
4256 default: break;
4257 case STATION_RAIL: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4258 case STATION_WAYPOINT: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4259 case STATION_AIRPORT: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4260 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);
4261 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);
4262 case STATION_BUOY: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY);
4263 case STATION_DOCK: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4264 case STATION_OILRIG:
4265 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG);
4266 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY);
4270 switch (GetStationType(tile)) {
4271 case STATION_RAIL: return RemoveRailStation(tile, flags);
4272 case STATION_WAYPOINT: return RemoveRailWaypoint(tile, flags);
4273 case STATION_AIRPORT: return RemoveAirport(tile, flags);
4274 case STATION_TRUCK:
4275 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4276 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4278 return RemoveRoadStop(tile, flags);
4279 case STATION_BUS:
4280 if (IsDriveThroughStopTile(tile) && !CanRemoveRoadWithStop(tile, flags)) {
4281 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4283 return RemoveRoadStop(tile, flags);
4284 case STATION_BUOY: return RemoveBuoy(tile, flags);
4285 case STATION_DOCK: return RemoveDock(tile, flags);
4286 default: break;
4289 return CMD_ERROR;
4292 static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
4294 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4295 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4296 * TTDP does not call it.
4298 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4299 switch (GetStationType(tile)) {
4300 case STATION_WAYPOINT:
4301 case STATION_RAIL: {
4302 DiagDirection direction = AxisToDiagDir(GetRailStationAxis(tile));
4303 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4304 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4305 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4308 case STATION_AIRPORT:
4309 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4311 case STATION_TRUCK:
4312 case STATION_BUS: {
4313 DiagDirection direction = GetRoadStopDir(tile);
4314 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, direction)) break;
4315 if (IsDriveThroughStopTile(tile)) {
4316 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, ReverseDiagDir(direction))) break;
4318 return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
4321 default: break;
4325 return Command<CMD_LANDSCAPE_CLEAR>::Do(flags, tile);
4329 * Get flow for a station.
4330 * @param st Station to get flow for.
4331 * @return Flow for st.
4333 uint FlowStat::GetShare(StationID st) const
4335 uint32 prev = 0;
4336 for (SharesMap::const_iterator it = this->shares.begin(); it != this->shares.end(); ++it) {
4337 if (it->second == st) {
4338 return it->first - prev;
4339 } else {
4340 prev = it->first;
4343 return 0;
4347 * Get a station a package can be routed to, but exclude the given ones.
4348 * @param excluded StationID not to be selected.
4349 * @param excluded2 Another StationID not to be selected.
4350 * @return A station ID from the shares map.
4352 StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4354 if (this->unrestricted == 0) return INVALID_STATION;
4355 assert(!this->shares.empty());
4356 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
4357 assert(it != this->shares.end() && it->first <= this->unrestricted);
4358 if (it->second != excluded && it->second != excluded2) return it->second;
4360 /* We've hit one of the excluded stations.
4361 * Draw another share, from outside its range. */
4363 uint end = it->first;
4364 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
4365 uint interval = end - begin;
4366 if (interval >= this->unrestricted) return INVALID_STATION; // Only one station in the map.
4367 uint new_max = this->unrestricted - interval;
4368 uint rand = RandomRange(new_max);
4369 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
4370 this->shares.upper_bound(rand + interval);
4371 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
4372 if (it2->second != excluded && it2->second != excluded2) return it2->second;
4374 /* We've hit the second excluded station.
4375 * Same as before, only a bit more complicated. */
4377 uint end2 = it2->first;
4378 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
4379 uint interval2 = end2 - begin2;
4380 if (interval2 >= new_max) return INVALID_STATION; // Only the two excluded stations in the map.
4381 new_max -= interval2;
4382 if (begin > begin2) {
4383 Swap(begin, begin2);
4384 Swap(end, end2);
4385 Swap(interval, interval2);
4387 rand = RandomRange(new_max);
4388 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
4389 if (rand < begin) {
4390 it3 = this->shares.upper_bound(rand);
4391 } else if (rand < begin2 - interval) {
4392 it3 = this->shares.upper_bound(rand + interval);
4393 } else {
4394 it3 = this->shares.upper_bound(rand + interval + interval2);
4396 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
4397 return it3->second;
4401 * Reduce all flows to minimum capacity so that they don't get in the way of
4402 * link usage statistics too much. Keep them around, though, to continue
4403 * routing any remaining cargo.
4405 void FlowStat::Invalidate()
4407 assert(!this->shares.empty());
4408 SharesMap new_shares;
4409 uint i = 0;
4410 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4411 new_shares[++i] = it->second;
4412 if (it->first == this->unrestricted) this->unrestricted = i;
4414 this->shares.swap(new_shares);
4415 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
4419 * Change share for specified station. By specifying INT_MIN as parameter you
4420 * can erase a share. Newly added flows will be unrestricted.
4421 * @param st Next Hop to be removed.
4422 * @param flow Share to be added or removed.
4424 void FlowStat::ChangeShare(StationID st, int flow)
4426 /* We assert only before changing as afterwards the shares can actually
4427 * be empty. In that case the whole flow stat must be deleted then. */
4428 assert(!this->shares.empty());
4430 uint removed_shares = 0;
4431 uint added_shares = 0;
4432 uint last_share = 0;
4433 SharesMap new_shares;
4434 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4435 if (it->second == st) {
4436 if (flow < 0) {
4437 uint share = it->first - last_share;
4438 if (flow == INT_MIN || (uint)(-flow) >= share) {
4439 removed_shares += share;
4440 if (it->first <= this->unrestricted) this->unrestricted -= share;
4441 if (flow != INT_MIN) flow += share;
4442 last_share = it->first;
4443 continue; // remove the whole share
4445 removed_shares += (uint)(-flow);
4446 } else {
4447 added_shares += (uint)(flow);
4449 if (it->first <= this->unrestricted) this->unrestricted += flow;
4451 /* If we don't continue above the whole flow has been added or
4452 * removed. */
4453 flow = 0;
4455 new_shares[it->first + added_shares - removed_shares] = it->second;
4456 last_share = it->first;
4458 if (flow > 0) {
4459 new_shares[last_share + (uint)flow] = st;
4460 if (this->unrestricted < last_share) {
4461 this->ReleaseShare(st);
4462 } else {
4463 this->unrestricted += flow;
4466 this->shares.swap(new_shares);
4470 * Restrict a flow by moving it to the end of the map and decreasing the amount
4471 * of unrestricted flow.
4472 * @param st Station of flow to be restricted.
4474 void FlowStat::RestrictShare(StationID st)
4476 assert(!this->shares.empty());
4477 uint flow = 0;
4478 uint last_share = 0;
4479 SharesMap new_shares;
4480 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4481 if (flow == 0) {
4482 if (it->first > this->unrestricted) return; // Not present or already restricted.
4483 if (it->second == st) {
4484 flow = it->first - last_share;
4485 this->unrestricted -= flow;
4486 } else {
4487 new_shares[it->first] = it->second;
4489 } else {
4490 new_shares[it->first - flow] = it->second;
4492 last_share = it->first;
4494 if (flow == 0) return;
4495 new_shares[last_share + flow] = st;
4496 this->shares.swap(new_shares);
4497 assert(!this->shares.empty());
4501 * Release ("unrestrict") a flow by moving it to the begin of the map and
4502 * increasing the amount of unrestricted flow.
4503 * @param st Station of flow to be released.
4505 void FlowStat::ReleaseShare(StationID st)
4507 assert(!this->shares.empty());
4508 uint flow = 0;
4509 uint next_share = 0;
4510 bool found = false;
4511 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
4512 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
4513 if (found) {
4514 flow = next_share - it->first;
4515 this->unrestricted += flow;
4516 break;
4517 } else {
4518 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
4519 if (it->second == st) found = true;
4521 next_share = it->first;
4523 if (flow == 0) return;
4524 SharesMap new_shares;
4525 new_shares[flow] = st;
4526 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
4527 if (it->second != st) {
4528 new_shares[flow + it->first] = it->second;
4529 } else {
4530 flow = 0;
4533 this->shares.swap(new_shares);
4534 assert(!this->shares.empty());
4538 * Scale all shares from link graph's runtime to monthly values.
4539 * @param runtime Time the link graph has been running without compression.
4540 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4542 void FlowStat::ScaleToMonthly(uint runtime)
4544 assert(runtime > 0);
4545 SharesMap new_shares;
4546 uint share = 0;
4547 for (SharesMap::iterator i = this->shares.begin(); i != this->shares.end(); ++i) {
4548 share = std::max(share + 1, i->first * 30 / runtime);
4549 new_shares[share] = i->second;
4550 if (this->unrestricted == i->first) this->unrestricted = share;
4552 this->shares.swap(new_shares);
4556 * Add some flow from "origin", going via "via".
4557 * @param origin Origin of the flow.
4558 * @param via Next hop.
4559 * @param flow Amount of flow to be added.
4561 void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
4563 FlowStatMap::iterator origin_it = this->find(origin);
4564 if (origin_it == this->end()) {
4565 this->insert(std::make_pair(origin, FlowStat(via, flow)));
4566 } else {
4567 origin_it->second.ChangeShare(via, flow);
4568 assert(!origin_it->second.GetShares()->empty());
4573 * Pass on some flow, remembering it as invalid, for later subtraction from
4574 * locally consumed flow. This is necessary because we can't have negative
4575 * flows and we don't want to sort the flows before adding them up.
4576 * @param origin Origin of the flow.
4577 * @param via Next hop.
4578 * @param flow Amount of flow to be passed.
4580 void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
4582 FlowStatMap::iterator prev_it = this->find(origin);
4583 if (prev_it == this->end()) {
4584 FlowStat fs(via, flow);
4585 fs.AppendShare(INVALID_STATION, flow);
4586 this->insert(std::make_pair(origin, fs));
4587 } else {
4588 prev_it->second.ChangeShare(via, flow);
4589 prev_it->second.ChangeShare(INVALID_STATION, flow);
4590 assert(!prev_it->second.GetShares()->empty());
4595 * Subtract invalid flows from locally consumed flow.
4596 * @param self ID of own station.
4598 void FlowStatMap::FinalizeLocalConsumption(StationID self)
4600 for (FlowStatMap::iterator i = this->begin(); i != this->end(); ++i) {
4601 FlowStat &fs = i->second;
4602 uint local = fs.GetShare(INVALID_STATION);
4603 if (local > INT_MAX) { // make sure it fits in an int
4604 fs.ChangeShare(self, -INT_MAX);
4605 fs.ChangeShare(INVALID_STATION, -INT_MAX);
4606 local -= INT_MAX;
4608 fs.ChangeShare(self, -(int)local);
4609 fs.ChangeShare(INVALID_STATION, -(int)local);
4611 /* If the local share is used up there must be a share for some
4612 * remote station. */
4613 assert(!fs.GetShares()->empty());
4618 * Delete all flows at a station for specific cargo and destination.
4619 * @param via Remote station of flows to be deleted.
4620 * @return IDs of source stations for which the complete FlowStat, not only a
4621 * share, has been erased.
4623 StationIDStack FlowStatMap::DeleteFlows(StationID via)
4625 StationIDStack ret;
4626 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
4627 FlowStat &s_flows = f_it->second;
4628 s_flows.ChangeShare(via, INT_MIN);
4629 if (s_flows.GetShares()->empty()) {
4630 ret.Push(f_it->first);
4631 this->erase(f_it++);
4632 } else {
4633 ++f_it;
4636 return ret;
4640 * Restrict all flows at a station for specific cargo and destination.
4641 * @param via Remote station of flows to be restricted.
4643 void FlowStatMap::RestrictFlows(StationID via)
4645 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4646 it->second.RestrictShare(via);
4651 * Release all flows at a station for specific cargo and destination.
4652 * @param via Remote station of flows to be released.
4654 void FlowStatMap::ReleaseFlows(StationID via)
4656 for (FlowStatMap::iterator it = this->begin(); it != this->end(); ++it) {
4657 it->second.ReleaseShare(via);
4662 * Get the sum of all flows from this FlowStatMap.
4663 * @return sum of all flows.
4665 uint FlowStatMap::GetFlow() const
4667 uint ret = 0;
4668 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4669 ret += (--(i->second.GetShares()->end()))->first;
4671 return ret;
4675 * Get the sum of flows via a specific station from this FlowStatMap.
4676 * @param via Remote station to look for.
4677 * @return all flows for 'via' added up.
4679 uint FlowStatMap::GetFlowVia(StationID via) const
4681 uint ret = 0;
4682 for (FlowStatMap::const_iterator i = this->begin(); i != this->end(); ++i) {
4683 ret += i->second.GetShare(via);
4685 return ret;
4689 * Get the sum of flows from a specific station from this FlowStatMap.
4690 * @param from Origin station to look for.
4691 * @return all flows from 'from' added up.
4693 uint FlowStatMap::GetFlowFrom(StationID from) const
4695 FlowStatMap::const_iterator i = this->find(from);
4696 if (i == this->end()) return 0;
4697 return (--(i->second.GetShares()->end()))->first;
4701 * Get the flow from a specific station via a specific other station.
4702 * @param from Origin station to look for.
4703 * @param via Remote station to look for.
4704 * @return flow share originating at 'from' and going to 'via'.
4706 uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
4708 FlowStatMap::const_iterator i = this->find(from);
4709 if (i == this->end()) return 0;
4710 return i->second.GetShare(via);
4713 extern const TileTypeProcs _tile_type_station_procs = {
4714 DrawTile_Station, // draw_tile_proc
4715 GetSlopePixelZ_Station, // get_slope_z_proc
4716 ClearTile_Station, // clear_tile_proc
4717 nullptr, // add_accepted_cargo_proc
4718 GetTileDesc_Station, // get_tile_desc_proc
4719 GetTileTrackStatus_Station, // get_tile_track_status_proc
4720 ClickTile_Station, // click_tile_proc
4721 AnimateTile_Station, // animate_tile_proc
4722 TileLoop_Station, // tile_loop_proc
4723 ChangeTileOwner_Station, // change_tile_owner_proc
4724 nullptr, // add_produced_cargo_proc
4725 VehicleEnter_Station, // vehicle_enter_tile_proc
4726 GetFoundation_Station, // get_foundation_proc
4727 TerraformTile_Station, // terraform_tile_proc