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/>.
8 /** @file station_cmd.cpp Handling of station tiles. */
12 #include "bridge_map.h"
13 #include "cmd_helper.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "command_func.h"
18 #include "news_func.h"
23 #include "newgrf_cargo.h"
24 #include "newgrf_debug.h"
25 #include "newgrf_station.h"
26 #include "newgrf_canal.h" /* For the buoy */
27 #include "pathfinder/yapf/yapf_cache.h"
28 #include "road_internal.h" /* For drawing catenary/checking road removal */
29 #include "autoslope.h"
31 #include "strings_func.h"
32 #include "clear_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "string_func.h"
36 #include "animated_tile_func.h"
37 #include "elrail_func.h"
38 #include "station_base.h"
39 #include "station_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"
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"
59 #include "table/strings.h"
61 #include "safeguards.h"
64 * Static instance of FlowStat::SharesMap.
65 * Note: This instance is created on task start.
66 * Lazy creation on first usage results in a data race between the CDist threads.
68 /* static */ const FlowStat::SharesMap
FlowStat::empty_sharesmap
;
71 * Check whether the given tile is a hangar.
72 * @param t the tile to of whether it is a hangar.
73 * @pre IsTileType(t, MP_STATION)
74 * @return true if and only if the tile is a hangar.
76 bool IsHangar(TileIndex t
)
78 assert(IsTileType(t
, MP_STATION
));
80 /* If the tile isn't an airport there's no chance it's a hangar. */
81 if (!IsAirport(t
)) return false;
83 const Station
*st
= Station::GetByTile(t
);
84 const AirportSpec
*as
= st
->airport
.GetSpec();
86 for (uint i
= 0; i
< as
->nof_depots
; i
++) {
87 if (st
->airport
.GetHangarTile(i
) == t
) return true;
94 * Look for a station owned by the given company around the given tile area.
95 * @param ta the area to search over
96 * @param closest_station the closest owned station found so far
97 * @param company the company whose stations to look for
98 * @param st to 'return' the found station
99 * @return Succeeded command (if zero or one station found) or failed command (for two or more stations found).
102 CommandCost
GetStationAround(TileArea ta
, StationID closest_station
, CompanyID company
, T
**st
)
106 /* check around to see if there are any stations there owned by the company */
107 TILE_AREA_LOOP(tile_cur
, ta
) {
108 if (IsTileType(tile_cur
, MP_STATION
)) {
109 StationID t
= GetStationIndex(tile_cur
);
110 if (!T::IsValidID(t
) || Station::Get(t
)->owner
!= company
) continue;
111 if (closest_station
== INVALID_STATION
) {
113 } else if (closest_station
!= t
) {
114 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
118 *st
= (closest_station
== INVALID_STATION
) ? nullptr : T::Get(closest_station
);
119 return CommandCost();
123 * Function to check whether the given tile matches some criterion.
124 * @param tile the tile to check
125 * @return true if it matches, false otherwise
127 typedef bool (*CMSAMatcher
)(TileIndex tile
);
130 * Counts the numbers of tiles matching a specific type in the area around
131 * @param tile the center tile of the 'count area'
132 * @param cmp the comparator/matcher (@see CMSAMatcher)
133 * @return the number of matching tiles around
135 static int CountMapSquareAround(TileIndex tile
, CMSAMatcher cmp
)
139 for (int dx
= -3; dx
<= 3; dx
++) {
140 for (int dy
= -3; dy
<= 3; dy
++) {
141 TileIndex t
= TileAddWrap(tile
, dx
, dy
);
142 if (t
!= INVALID_TILE
&& cmp(t
)) num
++;
150 * Check whether the tile is a mine.
151 * @param tile the tile to investigate.
152 * @return true if and only if the tile is a mine
154 static bool CMSAMine(TileIndex tile
)
157 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
159 const Industry
*ind
= Industry::GetByTile(tile
);
161 /* No extractive industry */
162 if ((GetIndustrySpec(ind
->type
)->life_type
& INDUSTRYLIFE_EXTRACTIVE
) == 0) return false;
164 for (uint i
= 0; i
< lengthof(ind
->produced_cargo
); i
++) {
165 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
166 * Also the production of passengers and mail is ignored. */
167 if (ind
->produced_cargo
[i
] != CT_INVALID
&&
168 (CargoSpec::Get(ind
->produced_cargo
[i
])->classes
& (CC_LIQUID
| CC_PASSENGERS
| CC_MAIL
)) == 0) {
177 * Check whether the tile is water.
178 * @param tile the tile to investigate.
179 * @return true if and only if the tile is a water tile
181 static bool CMSAWater(TileIndex tile
)
183 return IsTileType(tile
, MP_WATER
) && IsWater(tile
);
187 * Check whether the tile is a tree.
188 * @param tile the tile to investigate.
189 * @return true if and only if the tile is a tree tile
191 static bool CMSATree(TileIndex tile
)
193 return IsTileType(tile
, MP_TREES
);
196 #define M(x) ((x) - STR_SV_STNAME)
201 STATIONNAMING_AIRPORT
,
202 STATIONNAMING_OILRIG
,
204 STATIONNAMING_HELIPORT
,
207 /** Information to handle station action 0 property 24 correctly */
208 struct StationNameInformation
{
209 uint32 free_names
; ///< Current bitset of free names (we can remove names).
210 bool *indtypes
; ///< Array of bools telling whether an industry type has been found.
214 * Find a station action 0 property 24 station name, or reduce the
215 * free_names if needed.
216 * @param tile the tile to search
217 * @param user_data the StationNameInformation to base the search on
218 * @return true if the tile contains an industry that has not given
219 * its name to one of the other stations in town.
221 static bool FindNearIndustryName(TileIndex tile
, void *user_data
)
223 /* All already found industry types */
224 StationNameInformation
*sni
= (StationNameInformation
*)user_data
;
225 if (!IsTileType(tile
, MP_INDUSTRY
)) return false;
227 /* If the station name is undefined it means that it doesn't name a station */
228 IndustryType indtype
= GetIndustryType(tile
);
229 if (GetIndustrySpec(indtype
)->station_name
== STR_UNDEFINED
) return false;
231 /* In all cases if an industry that provides a name is found two of
232 * the standard names will be disabled. */
233 sni
->free_names
&= ~(1 << M(STR_SV_STNAME_OILFIELD
) | 1 << M(STR_SV_STNAME_MINES
));
234 return !sni
->indtypes
[indtype
];
237 static StringID
GenerateStationName(Station
*st
, TileIndex tile
, StationNaming name_class
)
239 static const uint32 _gen_station_name_bits
[] = {
240 0, // STATIONNAMING_RAIL
241 0, // STATIONNAMING_ROAD
242 1U << M(STR_SV_STNAME_AIRPORT
), // STATIONNAMING_AIRPORT
243 1U << M(STR_SV_STNAME_OILFIELD
), // STATIONNAMING_OILRIG
244 1U << M(STR_SV_STNAME_DOCKS
), // STATIONNAMING_DOCK
245 1U << M(STR_SV_STNAME_HELIPORT
), // STATIONNAMING_HELIPORT
248 const Town
*t
= st
->town
;
249 uint32 free_names
= UINT32_MAX
;
251 bool indtypes
[NUM_INDUSTRYTYPES
];
252 memset(indtypes
, 0, sizeof(indtypes
));
255 FOR_ALL_STATIONS(s
) {
256 if (s
!= st
&& s
->town
== t
) {
257 if (s
->indtype
!= IT_INVALID
) {
258 indtypes
[s
->indtype
] = true;
259 StringID name
= GetIndustrySpec(s
->indtype
)->station_name
;
260 if (name
!= STR_UNDEFINED
) {
261 /* Filter for other industrytypes with the same name */
262 for (IndustryType it
= 0; it
< NUM_INDUSTRYTYPES
; it
++) {
263 const IndustrySpec
*indsp
= GetIndustrySpec(it
);
264 if (indsp
->enabled
&& indsp
->station_name
== name
) indtypes
[it
] = true;
269 uint str
= M(s
->string_id
);
271 if (str
== M(STR_SV_STNAME_FOREST
)) {
272 str
= M(STR_SV_STNAME_WOODS
);
274 ClrBit(free_names
, str
);
279 TileIndex indtile
= tile
;
280 StationNameInformation sni
= { free_names
, indtypes
};
281 if (CircularTileSearch(&indtile
, 7, FindNearIndustryName
, &sni
)) {
282 /* An industry has been found nearby */
283 IndustryType indtype
= GetIndustryType(indtile
);
284 const IndustrySpec
*indsp
= GetIndustrySpec(indtype
);
285 /* STR_NULL means it only disables oil rig/mines */
286 if (indsp
->station_name
!= STR_NULL
) {
287 st
->indtype
= indtype
;
288 return STR_SV_STNAME_FALLBACK
;
292 /* Oil rigs/mines name could be marked not free by looking for a near by industry. */
293 free_names
= sni
.free_names
;
295 /* check default names */
296 uint32 tmp
= free_names
& _gen_station_name_bits
[name_class
];
297 if (tmp
!= 0) return STR_SV_STNAME
+ FindFirstBit(tmp
);
300 if (HasBit(free_names
, M(STR_SV_STNAME_MINES
))) {
301 if (CountMapSquareAround(tile
, CMSAMine
) >= 2) {
302 return STR_SV_STNAME_MINES
;
306 /* check close enough to town to get central as name? */
307 if (DistanceMax(tile
, t
->xy
) < 8) {
308 if (HasBit(free_names
, M(STR_SV_STNAME
))) return STR_SV_STNAME
;
310 if (HasBit(free_names
, M(STR_SV_STNAME_CENTRAL
))) return STR_SV_STNAME_CENTRAL
;
314 if (HasBit(free_names
, M(STR_SV_STNAME_LAKESIDE
)) &&
315 DistanceFromEdge(tile
) < 20 &&
316 CountMapSquareAround(tile
, CMSAWater
) >= 5) {
317 return STR_SV_STNAME_LAKESIDE
;
321 if (HasBit(free_names
, M(STR_SV_STNAME_WOODS
)) && (
322 CountMapSquareAround(tile
, CMSATree
) >= 8 ||
323 CountMapSquareAround(tile
, IsTileForestIndustry
) >= 2)
325 return _settings_game
.game_creation
.landscape
== LT_TROPIC
? STR_SV_STNAME_FOREST
: STR_SV_STNAME_WOODS
;
328 /* check elevation compared to town */
329 int z
= GetTileZ(tile
);
330 int z2
= GetTileZ(t
->xy
);
332 if (HasBit(free_names
, M(STR_SV_STNAME_VALLEY
))) return STR_SV_STNAME_VALLEY
;
334 if (HasBit(free_names
, M(STR_SV_STNAME_HEIGHTS
))) return STR_SV_STNAME_HEIGHTS
;
337 /* check direction compared to town */
338 static const int8 _direction_and_table
[] = {
339 ~( (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
340 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
341 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_EAST
)) | (1 << M(STR_SV_STNAME_NORTH
)) ),
342 ~( (1 << M(STR_SV_STNAME_SOUTH
)) | (1 << M(STR_SV_STNAME_WEST
)) | (1 << M(STR_SV_STNAME_EAST
)) ),
345 free_names
&= _direction_and_table
[
346 (TileX(tile
) < TileX(t
->xy
)) +
347 (TileY(tile
) < TileY(t
->xy
)) * 2];
349 tmp
= free_names
& ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 12) | (1 << 26) | (1 << 27) | (1 << 28) | (1 << 29) | (1 << 30));
350 return (tmp
== 0) ? STR_SV_STNAME_FALLBACK
: (STR_SV_STNAME
+ FindFirstBit(tmp
));
355 * Find the closest deleted station of the current company
356 * @param tile the tile to search from.
357 * @return the closest station or nullptr if too far.
359 static Station
*GetClosestDeletedStation(TileIndex tile
)
363 Station
*best_station
= nullptr;
364 ForAllStationsRadius(tile
, threshold
, [&](Station
*st
) {
365 if (!st
->IsInUse() && st
->owner
== _current_company
) {
366 uint cur_dist
= DistanceManhattan(tile
, st
->xy
);
368 if (cur_dist
< threshold
) {
369 threshold
= cur_dist
;
371 } else if (cur_dist
== threshold
&& best_station
!= nullptr) {
372 /* In case of a tie, lowest station ID wins */
373 if (st
->index
< best_station
->index
) best_station
= st
;
382 void Station::GetTileArea(TileArea
*ta
, StationType type
) const
386 *ta
= this->train_station
;
389 case STATION_AIRPORT
:
394 *ta
= this->truck_station
;
398 *ta
= this->bus_station
;
403 *ta
= this->docking_station
;
406 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()
454 FOR_ALL_BASE_STATIONS(st
) {
455 st
->UpdateVirtCoord();
460 * Get a mask of the cargo types that the station accepts.
461 * @param st Station to query
462 * @return the expected mask
464 static CargoTypes
GetAcceptanceMask(const Station
*st
)
468 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
469 if (HasBit(st
->goods
[i
].status
, GoodsEntry::GES_ACCEPTANCE
)) SetBit(mask
, i
);
475 * Items contains the two cargo names that are to be accepted or rejected.
476 * msg is the string id of the message to display.
478 static void ShowRejectOrAcceptNews(const Station
*st
, uint num_items
, CargoID
*cargo
, StringID msg
)
480 for (uint i
= 0; i
< num_items
; i
++) {
481 SetDParam(i
+ 1, CargoSpec::Get(cargo
[i
])->name
);
484 SetDParam(0, st
->index
);
485 AddNewsItem(msg
, NT_ACCEPTANCE
, NF_INCOLOUR
| NF_SMALL
, NR_STATION
, st
->index
);
489 * Get the cargo types being produced around the tile (in a rectangle).
490 * @param tile Northtile of area
491 * @param w X extent of the area
492 * @param h Y extent of the area
493 * @param rad Search radius in addition to the given area
495 CargoArray
GetProductionAroundTiles(TileIndex tile
, int w
, int h
, int rad
)
498 std::set
<IndustryID
> industries
;
499 TileArea ta
= TileArea(tile
, w
, h
).Expand(rad
);
501 /* Loop over all tiles to get the produced cargo of
502 * everything except industries */
503 TILE_AREA_LOOP(tile
, ta
) {
504 if (IsTileType(tile
, MP_INDUSTRY
)) industries
.insert(GetIndustryIndex(tile
));
505 AddProducedCargo(tile
, produced
);
508 /* Loop over the seen industries. They produce cargo for
509 * anything that is within 'rad' of any one of their tiles.
511 for (IndustryID industry
: industries
) {
512 const Industry
*i
= Industry::Get(industry
);
513 /* Skip industry with neutral station */
514 if (i
->neutral_station
!= nullptr && !_settings_game
.station
.serve_neutral_industries
) continue;
516 for (uint j
= 0; j
< lengthof(i
->produced_cargo
); j
++) {
517 CargoID cargo
= i
->produced_cargo
[j
];
518 if (cargo
!= CT_INVALID
) produced
[cargo
]++;
526 * Get the acceptance of cargoes around the tile in 1/8.
527 * @param tile Center of the search area
528 * @param w X extent of area
529 * @param h Y extent of area
530 * @param rad Search radius in addition to given area
531 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
532 * @param ind Industry associated with neutral station (e.g. oil rig) or nullptr
534 CargoArray
GetAcceptanceAroundTiles(TileIndex tile
, int w
, int h
, int rad
, CargoTypes
*always_accepted
)
536 CargoArray acceptance
;
537 if (always_accepted
!= nullptr) *always_accepted
= 0;
539 TileArea ta
= TileArea(tile
, w
, h
).Expand(rad
);
541 TILE_AREA_LOOP(tile
, ta
) {
542 /* Ignore industry if it has a neutral station. */
543 if (!_settings_game
.station
.serve_neutral_industries
&& IsTileType(tile
, MP_INDUSTRY
) && Industry::GetByTile(tile
)->neutral_station
!= nullptr) continue;
545 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
552 * Get the acceptance of cargoes around the station in.
553 * @param st Station to get acceptance of.
554 * @param always_accepted bitmask of cargo accepted by houses and headquarters; can be nullptr
556 static CargoArray
GetAcceptanceAroundStation(const Station
*st
, CargoTypes
*always_accepted
)
558 CargoArray acceptance
;
559 if (always_accepted
!= nullptr) *always_accepted
= 0;
561 BitmapTileIterator
it(st
->catchment_tiles
);
562 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
563 AddAcceptedCargo(tile
, acceptance
, always_accepted
);
570 * Update the acceptance for a station.
571 * @param st Station to update
572 * @param show_msg controls whether to display a message that acceptance was changed.
574 void UpdateStationAcceptance(Station
*st
, bool show_msg
)
576 /* old accepted goods types */
577 CargoTypes old_acc
= GetAcceptanceMask(st
);
579 /* And retrieve the acceptance. */
580 CargoArray acceptance
;
581 if (!st
->rect
.IsEmpty()) {
582 acceptance
= GetAcceptanceAroundStation(st
, &st
->always_accepted
);
585 /* Adjust in case our station only accepts fewer kinds of goods */
586 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
587 uint amt
= acceptance
[i
];
589 /* Make sure the station can accept the goods type. */
590 bool is_passengers
= IsCargoInClass(i
, CC_PASSENGERS
);
591 if ((!is_passengers
&& !(st
->facilities
& ~FACIL_BUS_STOP
)) ||
592 (is_passengers
&& !(st
->facilities
& ~FACIL_TRUCK_STOP
))) {
596 GoodsEntry
&ge
= st
->goods
[i
];
597 SB(ge
.status
, GoodsEntry::GES_ACCEPTANCE
, 1, amt
>= 8);
598 if (LinkGraph::IsValidID(ge
.link_graph
)) {
599 (*LinkGraph::Get(ge
.link_graph
))[ge
.node
].SetDemand(amt
/ 8);
603 /* Only show a message in case the acceptance was actually changed. */
604 CargoTypes new_acc
= GetAcceptanceMask(st
);
605 if (old_acc
== new_acc
) return;
607 /* show a message to report that the acceptance was changed? */
608 if (show_msg
&& st
->owner
== _local_company
&& st
->IsInUse()) {
609 /* List of accept and reject strings for different number of
611 static const StringID accept_msg
[] = {
612 STR_NEWS_STATION_NOW_ACCEPTS_CARGO
,
613 STR_NEWS_STATION_NOW_ACCEPTS_CARGO_AND_CARGO
,
615 static const StringID reject_msg
[] = {
616 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO
,
617 STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_OR_CARGO
,
620 /* Array of accepted and rejected cargo types */
621 CargoID accepts
[2] = { CT_INVALID
, CT_INVALID
};
622 CargoID rejects
[2] = { CT_INVALID
, CT_INVALID
};
626 /* Test each cargo type to see if its acceptance has changed */
627 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
628 if (HasBit(new_acc
, i
)) {
629 if (!HasBit(old_acc
, i
) && num_acc
< lengthof(accepts
)) {
630 /* New cargo is accepted */
631 accepts
[num_acc
++] = i
;
634 if (HasBit(old_acc
, i
) && num_rej
< lengthof(rejects
)) {
635 /* Old cargo is no longer accepted */
636 rejects
[num_rej
++] = i
;
641 /* Show news message if there are any changes */
642 if (num_acc
> 0) ShowRejectOrAcceptNews(st
, num_acc
, accepts
, accept_msg
[num_acc
- 1]);
643 if (num_rej
> 0) ShowRejectOrAcceptNews(st
, num_rej
, rejects
, reject_msg
[num_rej
- 1]);
646 /* redraw the station view since acceptance changed */
647 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_ACCEPT_RATING_LIST
);
650 static void UpdateStationSignCoord(BaseStation
*st
)
652 const StationRect
*r
= &st
->rect
;
654 if (r
->IsEmpty()) return; // no tiles belong to this station
656 /* clamp sign coord to be inside the station rect */
657 TileIndex new_xy
= TileXY(ClampU(TileX(st
->xy
), r
->left
, r
->right
), ClampU(TileY(st
->xy
), r
->top
, r
->bottom
));
658 st
->MoveSign(new_xy
);
660 if (!Station::IsExpected(st
)) return;
661 Station
*full_station
= Station::From(st
);
662 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
663 LinkGraphID lg
= full_station
->goods
[c
].link_graph
;
664 if (!LinkGraph::IsValidID(lg
)) continue;
665 (*LinkGraph::Get(lg
))[full_station
->goods
[c
].node
].UpdateLocation(st
->xy
);
670 * Common part of building various station parts and possibly attaching them to an existing one.
671 * @param[in,out] st Station to attach to
672 * @param flags Command flags
673 * @param reuse Whether to try to reuse a deleted station (gray sign) if possible
674 * @param area Area occupied by the new part
675 * @param name_class Station naming class to use to generate the new station's name
676 * @return Command error that occurred, if any
678 static CommandCost
BuildStationPart(Station
**st
, DoCommandFlag flags
, bool reuse
, TileArea area
, StationNaming name_class
)
680 /* Find a deleted station close to us */
681 if (*st
== nullptr && reuse
) *st
= GetClosestDeletedStation(area
.tile
);
683 if (*st
!= nullptr) {
684 if ((*st
)->owner
!= _current_company
) {
685 return_cmd_error(CMD_ERROR
);
688 CommandCost ret
= (*st
)->rect
.BeforeAddRect(area
.tile
, area
.w
, area
.h
, StationRect::ADD_TEST
);
689 if (ret
.Failed()) return ret
;
691 /* allocate and initialize new station */
692 if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING
);
694 if (flags
& DC_EXEC
) {
695 *st
= new Station(area
.tile
);
696 _station_kdtree
.Insert((*st
)->index
);
698 (*st
)->town
= ClosestTownFromTile(area
.tile
, UINT_MAX
);
699 (*st
)->string_id
= GenerateStationName(*st
, area
.tile
, name_class
);
701 if (Company::IsValidID(_current_company
)) {
702 SetBit((*st
)->town
->have_ratings
, _current_company
);
706 return CommandCost();
710 * This is called right after a station was deleted.
711 * It checks if the whole station is free of substations, and if so, the station will be
712 * deleted after a little while.
715 static void DeleteStationIfEmpty(BaseStation
*st
)
717 if (!st
->IsInUse()) {
719 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 0);
721 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
722 UpdateStationSignCoord(st
);
726 * After adding/removing tiles to station, update some station-related stuff.
727 * @param adding True if adding tiles, false if removing them.
728 * @param type StationType being modified.
730 void Station::AfterStationTileSetChange(bool adding
, StationType type
)
732 this->UpdateVirtCoord();
733 this->RecomputeCatchment();
734 DirtyCompanyInfrastructureWindows(this->owner
);
735 if (adding
) InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
739 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_TRAINS
);
741 case STATION_AIRPORT
:
745 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_ROADVEHS
);
748 SetWindowWidgetDirty(WC_STATION_VIEW
, this->index
, WID_SV_SHIPS
);
750 default: NOT_REACHED();
754 UpdateStationAcceptance(this, false);
755 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
757 DeleteStationIfEmpty(this);
762 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
);
765 * Checks if the given tile is buildable, flat and has a certain height.
766 * @param tile TileIndex to check.
767 * @param invalid_dirs Prohibited directions for slopes (set of #DiagDirection).
768 * @param allowed_z Height allowed for the tile. If allowed_z is negative, it will be set to the height of this tile.
769 * @param allow_steep Whether steep slopes are allowed.
770 * @param check_bridge Check for the existence of a bridge.
771 * @return The cost in case of success, or an error code if it failed.
773 CommandCost
CheckBuildableTile(TileIndex tile
, uint invalid_dirs
, int &allowed_z
, bool allow_steep
, bool check_bridge
= true)
775 if (check_bridge
&& IsBridgeAbove(tile
)) {
776 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
779 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
780 if (ret
.Failed()) return ret
;
783 Slope tileh
= GetTileSlope(tile
, &z
);
785 /* Prohibit building if
786 * 1) The tile is "steep" (i.e. stretches two height levels).
787 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
789 if ((!allow_steep
&& IsSteepSlope(tileh
)) ||
790 ((!_settings_game
.construction
.build_on_slopes
) && tileh
!= SLOPE_FLAT
)) {
791 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
794 CommandCost
cost(EXPENSES_CONSTRUCTION
);
795 int flat_z
= z
+ GetSlopeMaxZ(tileh
);
796 if (tileh
!= SLOPE_FLAT
) {
797 /* Forbid building if the tile faces a slope in a invalid direction. */
798 for (DiagDirection dir
= DIAGDIR_BEGIN
; dir
!= DIAGDIR_END
; dir
++) {
799 if (HasBit(invalid_dirs
, dir
) && !CanBuildDepotByTileh(dir
, tileh
)) {
800 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
803 cost
.AddCost(_price
[PR_BUILD_FOUNDATION
]);
806 /* The level of this tile must be equal to allowed_z. */
810 } else if (allowed_z
!= flat_z
) {
811 return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED
);
818 * Checks if an airport can be built at the given location and clear the area.
819 * @param tile_iter Airport tile iterator.
820 * @param flags Operation to perform.
821 * @return The cost in case of success, or an error code if it failed.
823 static CommandCost
CheckFlatLandAirport(AirportTileTableIterator tile_iter
, DoCommandFlag flags
)
825 CommandCost
cost(EXPENSES_CONSTRUCTION
);
828 for (; tile_iter
!= INVALID_TILE
; ++tile_iter
) {
829 CommandCost ret
= CheckBuildableTile(tile_iter
, 0, allowed_z
, true);
830 if (ret
.Failed()) return ret
;
833 ret
= DoCommand(tile_iter
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
834 if (ret
.Failed()) return ret
;
842 * Checks if a rail station can be built at the given area.
843 * @param tile_area Area to check.
844 * @param flags Operation to perform.
845 * @param axis Rail station axis.
846 * @param station StationID to be queried and returned if available.
847 * @param rt The rail type to check for (overbuilding rail stations over rail).
848 * @param affected_vehicles List of trains with PBS reservations on the tiles
849 * @param spec_class Station class.
850 * @param spec_index Index into the station class.
851 * @param plat_len Platform length.
852 * @param numtracks Number of platforms.
853 * @return The cost in case of success, or an error code if it failed.
855 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
)
857 CommandCost
cost(EXPENSES_CONSTRUCTION
);
859 uint invalid_dirs
= 5 << axis
;
861 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
862 bool slope_cb
= statspec
!= nullptr && HasBit(statspec
->callback_mask
, CBM_STATION_SLOPE_CHECK
);
864 TILE_AREA_LOOP(tile_cur
, tile_area
) {
865 CommandCost ret
= CheckBuildableTile(tile_cur
, invalid_dirs
, allowed_z
, false);
866 if (ret
.Failed()) return ret
;
870 /* Do slope check if requested. */
871 ret
= PerformStationTileSlopeCheck(tile_area
.tile
, tile_cur
, statspec
, axis
, plat_len
, numtracks
);
872 if (ret
.Failed()) return ret
;
875 /* if station is set, then we have special handling to allow building on top of already existing stations.
876 * so station points to INVALID_STATION if we can build on any station.
877 * Or it points to a station if we're only allowed to build on exactly that station. */
878 if (station
!= nullptr && IsTileType(tile_cur
, MP_STATION
)) {
879 if (!IsRailStation(tile_cur
)) {
880 return ClearTile_Station(tile_cur
, DC_AUTO
); // get error message
882 StationID st
= GetStationIndex(tile_cur
);
883 if (*station
== INVALID_STATION
) {
885 } else if (*station
!= st
) {
886 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
890 /* Rail type is only valid when building a railway station; if station to
891 * build isn't a rail station it's INVALID_RAILTYPE. */
892 if (rt
!= INVALID_RAILTYPE
&&
893 IsPlainRailTile(tile_cur
) && !HasSignals(tile_cur
) &&
894 HasPowerOnRail(GetRailType(tile_cur
), rt
)) {
895 /* Allow overbuilding if the tile:
896 * - has rail, but no signals
897 * - it has exactly one track
898 * - the track is in line with the station
899 * - the current rail type has power on the to-be-built type (e.g. convert normal rail to el rail)
901 TrackBits tracks
= GetTrackBits(tile_cur
);
902 Track track
= RemoveFirstTrack(&tracks
);
903 Track expected_track
= HasBit(invalid_dirs
, DIAGDIR_NE
) ? TRACK_X
: TRACK_Y
;
905 if (tracks
== TRACK_BIT_NONE
&& track
== expected_track
) {
906 /* Check for trains having a reservation for this tile. */
907 if (HasBit(GetRailReservationTrackBits(tile_cur
), track
)) {
908 Train
*v
= GetTrainForReservation(tile_cur
, track
);
910 affected_vehicles
.push_back(v
);
913 CommandCost ret
= DoCommand(tile_cur
, 0, track
, flags
, CMD_REMOVE_SINGLE_RAIL
);
914 if (ret
.Failed()) return ret
;
916 /* With flags & ~DC_EXEC CmdLandscapeClear would fail since the rail still exists */
920 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
921 if (ret
.Failed()) return ret
;
930 * Checks if a road stop can be built at the given tile.
931 * @param tile_area Area to check.
932 * @param flags Operation to perform.
933 * @param invalid_dirs Prohibited directions (set of DiagDirections).
934 * @param is_drive_through True if trying to build a drive-through station.
935 * @param is_truck_stop True when building a truck stop, false otherwise.
936 * @param axis Axis of a drive-through road stop.
937 * @param station StationID to be queried and returned if available.
938 * @param rt Road type to build.
939 * @return The cost in case of success, or an error code if it failed.
941 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
)
943 CommandCost
cost(EXPENSES_CONSTRUCTION
);
946 TILE_AREA_LOOP(cur_tile
, tile_area
) {
947 CommandCost ret
= CheckBuildableTile(cur_tile
, invalid_dirs
, allowed_z
, !is_drive_through
);
948 if (ret
.Failed()) return ret
;
951 /* If station is set, then we have special handling to allow building on top of already existing stations.
952 * Station points to INVALID_STATION if we can build on any station.
953 * Or it points to a station if we're only allowed to build on exactly that station. */
954 if (station
!= nullptr && IsTileType(cur_tile
, MP_STATION
)) {
955 if (!IsRoadStop(cur_tile
)) {
956 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
958 if (is_truck_stop
!= IsTruckStop(cur_tile
) ||
959 is_drive_through
!= IsDriveThroughStopTile(cur_tile
)) {
960 return ClearTile_Station(cur_tile
, DC_AUTO
); // Get error message.
962 /* Drive-through station in the wrong direction. */
963 if (is_drive_through
&& IsDriveThroughStopTile(cur_tile
) && DiagDirToAxis(GetRoadStopDir(cur_tile
)) != axis
){
964 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
966 StationID st
= GetStationIndex(cur_tile
);
967 if (*station
== INVALID_STATION
) {
969 } else if (*station
!= st
) {
970 return_cmd_error(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING
);
974 bool build_over_road
= is_drive_through
&& IsNormalRoadTile(cur_tile
);
975 /* Road bits in the wrong direction. */
976 RoadBits rb
= IsNormalRoadTile(cur_tile
) ? GetAllRoadBits(cur_tile
) : ROAD_NONE
;
977 if (build_over_road
&& (rb
& (axis
== AXIS_X
? ROAD_Y
: ROAD_X
)) != 0) {
978 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
979 switch (CountBits(rb
)) {
981 return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
984 if (rb
== ROAD_X
|| rb
== ROAD_Y
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_DIRECTION
);
985 return_cmd_error(STR_ERROR_DRIVE_THROUGH_CORNER
);
988 return_cmd_error(STR_ERROR_DRIVE_THROUGH_JUNCTION
);
992 if (build_over_road
) {
993 /* There is a road, check if we can build road+tram stop over it. */
994 RoadType road_rt
= GetRoadType(cur_tile
, RTT_ROAD
);
995 if (road_rt
!= INVALID_ROADTYPE
) {
996 Owner road_owner
= GetRoadOwner(cur_tile
, RTT_ROAD
);
997 if (road_owner
== OWNER_TOWN
) {
998 if (!_settings_game
.construction
.road_stop_on_town_road
) return_cmd_error(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD
);
999 } else if (!_settings_game
.construction
.road_stop_on_competitor_road
&& road_owner
!= OWNER_NONE
) {
1000 CommandCost ret
= CheckOwnership(road_owner
);
1001 if (ret
.Failed()) return ret
;
1003 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_ROAD
));
1005 if (RoadTypeIsRoad(rt
) && !HasPowerOnRoad(rt
, road_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1007 if (GetDisallowedRoadDirections(cur_tile
) != DRD_NONE
&& road_owner
!= OWNER_TOWN
) {
1008 CommandCost ret
= CheckOwnership(road_owner
);
1009 if (ret
.Failed()) return ret
;
1012 cost
.AddCost(RoadBuildCost(road_rt
) * (2 - num_pieces
));
1013 } else if (RoadTypeIsRoad(rt
)) {
1014 cost
.AddCost(RoadBuildCost(rt
) * 2);
1017 /* There is a tram, check if we can build road+tram stop over it. */
1018 RoadType tram_rt
= GetRoadType(cur_tile
, RTT_TRAM
);
1019 if (tram_rt
!= INVALID_ROADTYPE
) {
1020 Owner tram_owner
= GetRoadOwner(cur_tile
, RTT_TRAM
);
1021 if (Company::IsValidID(tram_owner
) &&
1022 (!_settings_game
.construction
.road_stop_on_competitor_road
||
1023 /* Disallow breaking end-of-line of someone else
1024 * so trams can still reverse on this tile. */
1025 HasExactlyOneBit(GetRoadBits(cur_tile
, RTT_TRAM
)))) {
1026 CommandCost ret
= CheckOwnership(tram_owner
);
1027 if (ret
.Failed()) return ret
;
1029 uint num_pieces
= CountBits(GetRoadBits(cur_tile
, RTT_TRAM
));
1031 if (RoadTypeIsTram(rt
) && !HasPowerOnRoad(rt
, tram_rt
)) return_cmd_error(STR_ERROR_NO_SUITABLE_ROAD
);
1033 cost
.AddCost(RoadBuildCost(tram_rt
) * (2 - num_pieces
));
1034 } else if (RoadTypeIsTram(rt
)) {
1035 cost
.AddCost(RoadBuildCost(rt
) * 2);
1038 ret
= DoCommand(cur_tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
1039 if (ret
.Failed()) return ret
;
1041 cost
.AddCost(RoadBuildCost(rt
) * 2);
1050 * Check whether we can expand the rail part of the given station.
1051 * @param st the station to expand
1052 * @param new_ta the current (and if all is fine new) tile area of the rail part of the station
1053 * @param axis the axis of the newly build rail
1054 * @return Succeeded or failed command.
1056 CommandCost
CanExpandRailStation(const BaseStation
*st
, TileArea
&new_ta
, Axis axis
)
1058 TileArea cur_ta
= st
->train_station
;
1060 /* determine new size of train station region.. */
1061 int x
= min(TileX(cur_ta
.tile
), TileX(new_ta
.tile
));
1062 int y
= min(TileY(cur_ta
.tile
), TileY(new_ta
.tile
));
1063 new_ta
.w
= max(TileX(cur_ta
.tile
) + cur_ta
.w
, TileX(new_ta
.tile
) + new_ta
.w
) - x
;
1064 new_ta
.h
= max(TileY(cur_ta
.tile
) + cur_ta
.h
, TileY(new_ta
.tile
) + new_ta
.h
) - y
;
1065 new_ta
.tile
= TileXY(x
, y
);
1067 /* make sure the final size is not too big. */
1068 if (new_ta
.w
> _settings_game
.station
.station_spread
|| new_ta
.h
> _settings_game
.station
.station_spread
) {
1069 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1072 return CommandCost();
1075 static inline byte
*CreateSingle(byte
*layout
, int n
)
1078 do *layout
++ = 0; while (--i
);
1079 layout
[((n
- 1) >> 1) - n
] = 2;
1083 static inline byte
*CreateMulti(byte
*layout
, int n
, byte b
)
1086 do *layout
++ = b
; while (--i
);
1089 layout
[n
- 1 - n
] = 0;
1095 * Create the station layout for the given number of tracks and platform length.
1096 * @param layout The layout to write to.
1097 * @param numtracks The number of tracks to write.
1098 * @param plat_len The length of the platforms.
1099 * @param statspec The specification of the station to (possibly) get the layout from.
1101 void GetStationLayout(byte
*layout
, int numtracks
, int plat_len
, const StationSpec
*statspec
)
1103 if (statspec
!= nullptr && statspec
->lengths
>= plat_len
&&
1104 statspec
->platforms
[plat_len
- 1] >= numtracks
&&
1105 statspec
->layouts
[plat_len
- 1][numtracks
- 1]) {
1106 /* Custom layout defined, follow it. */
1107 memcpy(layout
, statspec
->layouts
[plat_len
- 1][numtracks
- 1],
1108 plat_len
* numtracks
);
1112 if (plat_len
== 1) {
1113 CreateSingle(layout
, numtracks
);
1115 if (numtracks
& 1) layout
= CreateSingle(layout
, plat_len
);
1118 while (--numtracks
>= 0) {
1119 layout
= CreateMulti(layout
, plat_len
, 4);
1120 layout
= CreateMulti(layout
, plat_len
, 6);
1126 * Find a nearby station that joins this station.
1127 * @tparam T the class to find a station for
1128 * @tparam error_message the error message when building a station on top of others
1129 * @param existing_station an existing station we build over
1130 * @param station_to_join the station to join to
1131 * @param adjacent whether adjacent stations are allowed
1132 * @param ta the area of the newly build station
1133 * @param st 'return' pointer for the found station
1134 * @return command cost with the error or 'okay'
1136 template <class T
, StringID error_message
>
1137 CommandCost
FindJoiningBaseStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, T
**st
)
1139 assert(*st
== nullptr);
1140 bool check_surrounding
= true;
1142 if (_settings_game
.station
.adjacent_stations
) {
1143 if (existing_station
!= INVALID_STATION
) {
1144 if (adjacent
&& existing_station
!= station_to_join
) {
1145 /* You can't build an adjacent station over the top of one that
1146 * already exists. */
1147 return_cmd_error(error_message
);
1149 /* Extend the current station, and don't check whether it will
1150 * be near any other stations. */
1151 *st
= T::GetIfValid(existing_station
);
1152 check_surrounding
= (*st
== nullptr);
1155 /* There's no station here. Don't check the tiles surrounding this
1156 * one if the company wanted to build an adjacent station. */
1157 if (adjacent
) check_surrounding
= false;
1161 if (check_surrounding
) {
1162 /* Make sure there is no more than one other station around us that is owned by us. */
1163 CommandCost ret
= GetStationAround(ta
, existing_station
, _current_company
, st
);
1164 if (ret
.Failed()) return ret
;
1168 if (*st
== nullptr && station_to_join
!= INVALID_STATION
) *st
= T::GetIfValid(station_to_join
);
1170 return CommandCost();
1174 * Find a nearby station that joins this station.
1175 * @param existing_station an existing station we build over
1176 * @param station_to_join the station to join to
1177 * @param adjacent whether adjacent stations are allowed
1178 * @param ta the area of the newly build station
1179 * @param st 'return' pointer for the found station
1180 * @return command cost with the error or 'okay'
1182 static CommandCost
FindJoiningStation(StationID existing_station
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1184 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST
>(existing_station
, station_to_join
, adjacent
, ta
, st
);
1188 * Find a nearby waypoint that joins this waypoint.
1189 * @param existing_waypoint an existing waypoint we build over
1190 * @param waypoint_to_join the waypoint to join to
1191 * @param adjacent whether adjacent waypoints are allowed
1192 * @param ta the area of the newly build waypoint
1193 * @param wp 'return' pointer for the found waypoint
1194 * @return command cost with the error or 'okay'
1196 CommandCost
FindJoiningWaypoint(StationID existing_waypoint
, StationID waypoint_to_join
, bool adjacent
, TileArea ta
, Waypoint
**wp
)
1198 return FindJoiningBaseStation
<Waypoint
, STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST
>(existing_waypoint
, waypoint_to_join
, adjacent
, ta
, wp
);
1202 * Clear platform reservation during station building/removing.
1203 * @param v vehicle which holds reservation
1205 static void FreeTrainReservation(Train
*v
)
1207 FreeTrainTrackReservation(v
);
1208 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), false);
1210 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), false);
1214 * Restore platform reservation during station building/removing.
1215 * @param v vehicle which held reservation
1217 static void RestoreTrainReservation(Train
*v
)
1219 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(v
->GetVehicleTrackdir()), true);
1220 TryPathReserve(v
, true, true);
1222 if (IsRailStationTile(v
->tile
)) SetRailStationPlatformReservation(v
->tile
, TrackdirToExitdir(ReverseTrackdir(v
->GetVehicleTrackdir())), true);
1226 * Build rail station
1227 * @param tile_org northern most position of station dragging/placement
1228 * @param flags operation to perform
1229 * @param p1 various bitstuffed elements
1230 * - p1 = (bit 0- 5) - railtype
1231 * - p1 = (bit 6) - orientation (Axis)
1232 * - p1 = (bit 8-15) - number of tracks
1233 * - p1 = (bit 16-23) - platform length
1234 * - p1 = (bit 24) - allow stations directly adjacent to other stations.
1235 * @param p2 various bitstuffed elements
1236 * - p2 = (bit 0- 7) - custom station class
1237 * - p2 = (bit 8-15) - custom station id
1238 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
1239 * @param text unused
1240 * @return the cost of this operation or an error
1242 CommandCost
CmdBuildRailStation(TileIndex tile_org
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1244 /* Unpack parameters */
1245 RailType rt
= Extract
<RailType
, 0, 6>(p1
);
1246 Axis axis
= Extract
<Axis
, 6, 1>(p1
);
1247 byte numtracks
= GB(p1
, 8, 8);
1248 byte plat_len
= GB(p1
, 16, 8);
1249 bool adjacent
= HasBit(p1
, 24);
1251 StationClassID spec_class
= Extract
<StationClassID
, 0, 8>(p2
);
1252 byte spec_index
= GB(p2
, 8, 8);
1253 StationID station_to_join
= GB(p2
, 16, 16);
1255 /* Does the authority allow this? */
1256 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile_org
, flags
);
1257 if (ret
.Failed()) return ret
;
1259 if (!ValParamRailtype(rt
)) return CMD_ERROR
;
1261 /* Check if the given station class is valid */
1262 if ((uint
)spec_class
>= StationClass::GetClassCount() || spec_class
== STAT_CLASS_WAYP
) return CMD_ERROR
;
1263 if (spec_index
>= StationClass::Get(spec_class
)->GetSpecCount()) return CMD_ERROR
;
1264 if (plat_len
== 0 || numtracks
== 0) return CMD_ERROR
;
1267 if (axis
== AXIS_X
) {
1275 bool reuse
= (station_to_join
!= NEW_STATION
);
1276 if (!reuse
) station_to_join
= INVALID_STATION
;
1277 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1279 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1281 if (h_org
> _settings_game
.station
.station_spread
|| w_org
> _settings_game
.station
.station_spread
) return CMD_ERROR
;
1283 /* these values are those that will be stored in train_tile and station_platforms */
1284 TileArea
new_location(tile_org
, w_org
, h_org
);
1286 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1287 StationID est
= INVALID_STATION
;
1288 std::vector
<Train
*> affected_vehicles
;
1289 /* Clear the land below the station. */
1290 CommandCost cost
= CheckFlatLandRailStation(new_location
, flags
, axis
, &est
, rt
, affected_vehicles
, spec_class
, spec_index
, plat_len
, numtracks
);
1291 if (cost
.Failed()) return cost
;
1292 /* Add construction expenses. */
1293 cost
.AddCost((numtracks
* _price
[PR_BUILD_STATION_RAIL
] + _price
[PR_BUILD_STATION_RAIL_LENGTH
]) * plat_len
);
1294 cost
.AddCost(numtracks
* plat_len
* RailBuildCost(rt
));
1296 Station
*st
= nullptr;
1297 ret
= FindJoiningStation(est
, station_to_join
, adjacent
, new_location
, &st
);
1298 if (ret
.Failed()) return ret
;
1300 ret
= BuildStationPart(&st
, flags
, reuse
, new_location
, STATIONNAMING_RAIL
);
1301 if (ret
.Failed()) return ret
;
1303 if (st
!= nullptr && st
->train_station
.tile
!= INVALID_TILE
) {
1304 CommandCost ret
= CanExpandRailStation(st
, new_location
, axis
);
1305 if (ret
.Failed()) return ret
;
1308 /* Check if we can allocate a custom stationspec to this station */
1309 const StationSpec
*statspec
= StationClass::Get(spec_class
)->GetSpec(spec_index
);
1310 int specindex
= AllocateSpecToStation(statspec
, st
, (flags
& DC_EXEC
) != 0);
1311 if (specindex
== -1) return_cmd_error(STR_ERROR_TOO_MANY_STATION_SPECS
);
1313 if (statspec
!= nullptr) {
1314 /* Perform NewStation checks */
1316 /* Check if the station size is permitted */
1317 if (HasBit(statspec
->disallowed_platforms
, min(numtracks
- 1, 7)) || HasBit(statspec
->disallowed_lengths
, min(plat_len
- 1, 7))) {
1321 /* Check if the station is buildable */
1322 if (HasBit(statspec
->callback_mask
, CBM_STATION_AVAIL
)) {
1323 uint16 cb_res
= GetStationCallback(CBID_STATION_AVAILABILITY
, 0, 0, statspec
, nullptr, INVALID_TILE
);
1324 if (cb_res
!= CALLBACK_FAILED
&& !Convert8bitBooleanCallback(statspec
->grf_prop
.grffile
, CBID_STATION_AVAILABILITY
, cb_res
)) return CMD_ERROR
;
1328 if (flags
& DC_EXEC
) {
1329 TileIndexDiff tile_delta
;
1331 byte numtracks_orig
;
1334 st
->train_station
= new_location
;
1335 st
->AddFacility(FACIL_TRAIN
, new_location
.tile
);
1337 st
->rect
.BeforeAddRect(tile_org
, w_org
, h_org
, StationRect::ADD_TRY
);
1339 if (statspec
!= nullptr) {
1340 /* Include this station spec's animation trigger bitmask
1341 * in the station's cached copy. */
1342 st
->cached_anim_triggers
|= statspec
->animation
.triggers
;
1345 tile_delta
= (axis
== AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
1346 track
= AxisToTrack(axis
);
1348 layout_ptr
= AllocaM(byte
, numtracks
* plat_len
);
1349 GetStationLayout(layout_ptr
, numtracks
, plat_len
, statspec
);
1351 numtracks_orig
= numtracks
;
1353 Company
*c
= Company::Get(st
->owner
);
1354 TileIndex tile_track
= tile_org
;
1356 TileIndex tile
= tile_track
;
1359 byte layout
= *layout_ptr
++;
1360 if (IsRailStationTile(tile
) && HasStationReservation(tile
)) {
1361 /* Check for trains having a reservation for this tile. */
1362 Train
*v
= GetTrainForReservation(tile
, AxisToTrack(GetRailStationAxis(tile
)));
1364 affected_vehicles
.push_back(v
);
1365 FreeTrainReservation(v
);
1369 /* Railtype can change when overbuilding. */
1370 if (IsRailStationTile(tile
)) {
1371 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[GetRailType(tile
)]--;
1372 c
->infrastructure
.station
--;
1375 /* Remove animation if overbuilding */
1376 DeleteAnimatedTile(tile
);
1377 byte old_specindex
= HasStationTileRail(tile
) ? GetCustomStationSpecIndex(tile
) : 0;
1378 MakeRailStation(tile
, st
->owner
, st
->index
, axis
, layout
& ~1, rt
);
1379 /* Free the spec if we overbuild something */
1380 DeallocateSpecFromStation(st
, old_specindex
);
1382 SetCustomStationSpecIndex(tile
, specindex
);
1383 SetStationTileRandomBits(tile
, GB(Random(), 0, 4));
1384 SetAnimationFrame(tile
, 0);
1386 if (!IsStationTileBlocked(tile
)) c
->infrastructure
.rail
[rt
]++;
1387 c
->infrastructure
.station
++;
1389 if (statspec
!= nullptr) {
1390 /* Use a fixed axis for GetPlatformInfo as our platforms / numtracks are always the right way around */
1391 uint32 platinfo
= GetPlatformInfo(AXIS_X
, GetStationGfx(tile
), plat_len
, numtracks_orig
, plat_len
- w
, numtracks_orig
- numtracks
, false);
1393 /* As the station is not yet completely finished, the station does not yet exist. */
1394 uint16 callback
= GetStationCallback(CBID_STATION_TILE_LAYOUT
, platinfo
, 0, statspec
, nullptr, tile
);
1395 if (callback
!= CALLBACK_FAILED
) {
1397 SetStationGfx(tile
, (callback
& ~1) + axis
);
1399 ErrorUnknownCallbackResult(statspec
->grf_prop
.grffile
->grfid
, CBID_STATION_TILE_LAYOUT
, callback
);
1403 /* Trigger station animation -- after building? */
1404 TriggerStationAnimation(st
, tile
, SAT_BUILT
);
1409 AddTrackToSignalBuffer(tile_track
, track
, _current_company
);
1410 YapfNotifyTrackLayoutChange(tile_track
, track
);
1411 tile_track
+= tile_delta
^ TileDiffXY(1, 1); // perpendicular to tile_delta
1412 } while (--numtracks
);
1414 for (uint i
= 0; i
< affected_vehicles
.size(); ++i
) {
1415 /* Restore reservations of trains. */
1416 RestoreTrainReservation(affected_vehicles
[i
]);
1419 /* Check whether we need to expand the reservation of trains already on the station. */
1420 TileArea update_reservation_area
;
1421 if (axis
== AXIS_X
) {
1422 update_reservation_area
= TileArea(tile_org
, 1, numtracks_orig
);
1424 update_reservation_area
= TileArea(tile_org
, numtracks_orig
, 1);
1427 TILE_AREA_LOOP(tile
, update_reservation_area
) {
1428 /* Don't even try to make eye candy parts reserved. */
1429 if (IsStationTileBlocked(tile
)) continue;
1431 DiagDirection dir
= AxisToDiagDir(axis
);
1432 TileIndexDiff tile_offset
= TileOffsByDiagDir(dir
);
1433 TileIndex platform_begin
= tile
;
1434 TileIndex platform_end
= tile
;
1436 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1437 for (TileIndex next_tile
= platform_begin
- tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_begin
); next_tile
-= tile_offset
) {
1438 platform_begin
= next_tile
;
1440 for (TileIndex next_tile
= platform_end
+ tile_offset
; IsCompatibleTrainStationTile(next_tile
, platform_end
); next_tile
+= tile_offset
) {
1441 platform_end
= next_tile
;
1444 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1445 bool reservation
= false;
1446 for (TileIndex t
= platform_begin
; !reservation
&& t
<= platform_end
; t
+= tile_offset
) {
1447 reservation
= HasStationReservation(t
);
1451 SetRailStationPlatformReservation(platform_begin
, dir
, true);
1455 st
->MarkTilesDirty(false);
1456 st
->AfterStationTileSetChange(true, STATION_RAIL
);
1462 static TileArea
MakeStationAreaSmaller(BaseStation
*st
, TileArea ta
, bool (*func
)(BaseStation
*, TileIndex
))
1467 if (ta
.w
!= 0 && ta
.h
!= 0) {
1468 /* check the left side, x = constant, y changes */
1469 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(0, i
));) {
1470 /* the left side is unused? */
1472 ta
.tile
+= TileDiffXY(1, 0);
1478 /* check the right side, x = constant, y changes */
1479 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(ta
.w
- 1, i
));) {
1480 /* the right side is unused? */
1487 /* check the upper side, y = constant, x changes */
1488 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, 0));) {
1489 /* the left side is unused? */
1491 ta
.tile
+= TileDiffXY(0, 1);
1497 /* check the lower side, y = constant, x changes */
1498 for (uint i
= 0; !func(st
, ta
.tile
+ TileDiffXY(i
, ta
.h
- 1));) {
1499 /* the left side is unused? */
1512 static bool TileBelongsToRailStation(BaseStation
*st
, TileIndex tile
)
1514 return st
->TileBelongsToRailStation(tile
);
1517 static void MakeRailStationAreaSmaller(BaseStation
*st
)
1519 st
->train_station
= MakeStationAreaSmaller(st
, st
->train_station
, TileBelongsToRailStation
);
1522 static bool TileBelongsToShipStation(BaseStation
*st
, TileIndex tile
)
1524 return IsDockTile(tile
) && GetStationIndex(tile
) == st
->index
;
1527 static void MakeShipStationAreaSmaller(Station
*st
)
1529 st
->ship_station
= MakeStationAreaSmaller(st
, st
->ship_station
, TileBelongsToShipStation
);
1530 UpdateStationDockingTiles(st
);
1534 * Remove a number of tiles from any rail station within the area.
1535 * @param ta the area to clear station tile from.
1536 * @param affected_stations the stations affected.
1537 * @param flags the command flags.
1538 * @param removal_cost the cost for removing the tile, including the rail.
1539 * @param keep_rail whether to keep the rail of the station.
1540 * @tparam T the type of station to remove.
1541 * @return the number of cleared tiles or an error.
1544 CommandCost
RemoveFromRailBaseStation(TileArea ta
, std::vector
<T
*> &affected_stations
, DoCommandFlag flags
, Money removal_cost
, bool keep_rail
)
1546 /* Count of the number of tiles removed */
1548 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
1549 /* Accumulator for the errors seen during clearing. If no errors happen,
1550 * and the quantity is 0 there is no station. Otherwise it will be one
1551 * of the other error that got accumulated. */
1554 /* Do the action for every tile into the area */
1555 TILE_AREA_LOOP(tile
, ta
) {
1556 /* Make sure the specified tile is a rail station */
1557 if (!HasStationTileRail(tile
)) continue;
1559 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1560 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
1562 if (ret
.Failed()) continue;
1564 /* Check ownership of station */
1565 T
*st
= T::GetByTile(tile
);
1566 if (st
== nullptr) continue;
1568 if (_current_company
!= OWNER_WATER
) {
1569 CommandCost ret
= CheckOwnership(st
->owner
);
1571 if (ret
.Failed()) continue;
1574 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1577 if (keep_rail
|| IsStationTileBlocked(tile
)) {
1578 /* Don't refund the 'steel' of the track when we keep the
1579 * rail, or when the tile didn't have any rail at all. */
1580 total_cost
.AddCost(-_price
[PR_CLEAR_RAIL
]);
1583 if (flags
& DC_EXEC
) {
1584 /* read variables before the station tile is removed */
1585 uint specindex
= GetCustomStationSpecIndex(tile
);
1586 Track track
= GetRailStationTrack(tile
);
1587 Owner owner
= GetTileOwner(tile
);
1588 RailType rt
= GetRailType(tile
);
1591 if (HasStationReservation(tile
)) {
1592 v
= GetTrainForReservation(tile
, track
);
1593 if (v
!= nullptr) FreeTrainReservation(v
);
1596 bool build_rail
= keep_rail
&& !IsStationTileBlocked(tile
);
1597 if (!build_rail
&& !IsStationTileBlocked(tile
)) Company::Get(owner
)->infrastructure
.rail
[rt
]--;
1599 DoClearSquare(tile
);
1600 DeleteNewGRFInspectWindow(GSF_STATIONS
, tile
);
1601 if (build_rail
) MakeRailNormal(tile
, owner
, TrackToTrackBits(track
), rt
);
1602 Company::Get(owner
)->infrastructure
.station
--;
1603 DirtyCompanyInfrastructureWindows(owner
);
1605 st
->rect
.AfterRemoveTile(st
, tile
);
1606 AddTrackToSignalBuffer(tile
, track
, owner
);
1607 YapfNotifyTrackLayoutChange(tile
, track
);
1609 DeallocateSpecFromStation(st
, specindex
);
1611 include(affected_stations
, st
);
1613 if (v
!= nullptr) RestoreTrainReservation(v
);
1617 if (quantity
== 0) return error
.Failed() ? error
: CommandCost(STR_ERROR_THERE_IS_NO_STATION
);
1619 for (T
*st
: affected_stations
) {
1621 /* now we need to make the "spanned" area of the railway station smaller
1622 * if we deleted something at the edges.
1623 * we also need to adjust train_tile. */
1624 MakeRailStationAreaSmaller(st
);
1625 UpdateStationSignCoord(st
);
1627 /* if we deleted the whole station, delete the train facility. */
1628 if (st
->train_station
.tile
== INVALID_TILE
) {
1629 st
->facilities
&= ~FACIL_TRAIN
;
1630 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1631 st
->UpdateVirtCoord();
1632 DeleteStationIfEmpty(st
);
1636 total_cost
.AddCost(quantity
* removal_cost
);
1641 * Remove a single tile from a rail station.
1642 * This allows for custom-built station with holes and weird layouts
1643 * @param start tile of station piece to remove
1644 * @param flags operation to perform
1645 * @param p1 start_tile
1646 * @param p2 various bitstuffed elements
1647 * - p2 = bit 0 - if set keep the rail
1648 * @param text unused
1649 * @return the cost of this operation or an error
1651 CommandCost
CmdRemoveFromRailStation(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1653 TileIndex end
= p1
== 0 ? start
: p1
;
1654 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1656 TileArea
ta(start
, end
);
1657 std::vector
<Station
*> affected_stations
;
1659 CommandCost ret
= RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_STATION_RAIL
], HasBit(p2
, 0));
1660 if (ret
.Failed()) return ret
;
1662 /* Do all station specific functions here. */
1663 for (Station
*st
: affected_stations
) {
1665 if (st
->train_station
.tile
== INVALID_TILE
) SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_TRAINS
);
1666 st
->MarkTilesDirty(false);
1667 st
->RecomputeCatchment();
1670 /* Now apply the rail cost to the number that we deleted */
1675 * Remove a single tile from a waypoint.
1676 * This allows for custom-built waypoint with holes and weird layouts
1677 * @param start tile of waypoint piece to remove
1678 * @param flags operation to perform
1679 * @param p1 start_tile
1680 * @param p2 various bitstuffed elements
1681 * - p2 = bit 0 - if set keep the rail
1682 * @param text unused
1683 * @return the cost of this operation or an error
1685 CommandCost
CmdRemoveFromRailWaypoint(TileIndex start
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1687 TileIndex end
= p1
== 0 ? start
: p1
;
1688 if (start
>= MapSize() || end
>= MapSize()) return CMD_ERROR
;
1690 TileArea
ta(start
, end
);
1691 std::vector
<Waypoint
*> affected_stations
;
1693 return RemoveFromRailBaseStation(ta
, affected_stations
, flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
], HasBit(p2
, 0));
1698 * Remove a rail station/waypoint
1699 * @param st The station/waypoint to remove the rail part from
1700 * @param flags operation to perform
1701 * @param removal_cost the cost for removing a tile
1702 * @tparam T the type of station to remove
1703 * @return cost or failure of operation
1706 CommandCost
RemoveRailStation(T
*st
, DoCommandFlag flags
, Money removal_cost
)
1708 /* Current company owns the station? */
1709 if (_current_company
!= OWNER_WATER
) {
1710 CommandCost ret
= CheckOwnership(st
->owner
);
1711 if (ret
.Failed()) return ret
;
1714 /* determine width and height of platforms */
1715 TileArea ta
= st
->train_station
;
1717 assert(ta
.w
!= 0 && ta
.h
!= 0);
1719 CommandCost
cost(EXPENSES_CONSTRUCTION
);
1720 /* clear all areas of the station */
1721 TILE_AREA_LOOP(tile
, ta
) {
1722 /* only remove tiles that are actually train station tiles */
1723 if (st
->TileBelongsToRailStation(tile
)) {
1724 std::vector
<T
*> affected_stations
; // dummy
1725 CommandCost ret
= RemoveFromRailBaseStation(TileArea(tile
, 1, 1), affected_stations
, flags
, removal_cost
, false);
1726 if (ret
.Failed()) return ret
;
1735 * Remove a rail station
1736 * @param tile Tile of the station.
1737 * @param flags operation to perform
1738 * @return cost or failure of operation
1740 static CommandCost
RemoveRailStation(TileIndex tile
, DoCommandFlag flags
)
1742 /* if there is flooding, remove platforms tile by tile */
1743 if (_current_company
== OWNER_WATER
) {
1744 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_STATION
);
1747 Station
*st
= Station::GetByTile(tile
);
1748 CommandCost cost
= RemoveRailStation(st
, flags
, _price
[PR_CLEAR_STATION_RAIL
]);
1750 if (flags
& DC_EXEC
) st
->RecomputeCatchment();
1756 * Remove a rail waypoint
1757 * @param tile Tile of the waypoint.
1758 * @param flags operation to perform
1759 * @return cost or failure of operation
1761 static CommandCost
RemoveRailWaypoint(TileIndex tile
, DoCommandFlag flags
)
1763 /* if there is flooding, remove waypoints tile by tile */
1764 if (_current_company
== OWNER_WATER
) {
1765 return DoCommand(tile
, 0, 0, DC_EXEC
, CMD_REMOVE_FROM_RAIL_WAYPOINT
);
1768 return RemoveRailStation(Waypoint::GetByTile(tile
), flags
, _price
[PR_CLEAR_WAYPOINT_RAIL
]);
1773 * @param truck_station Determines whether a stop is #ROADSTOP_BUS or #ROADSTOP_TRUCK
1774 * @param st The Station to do the whole procedure for
1775 * @return a pointer to where to link a new RoadStop*
1777 static RoadStop
**FindRoadStopSpot(bool truck_station
, Station
*st
)
1779 RoadStop
**primary_stop
= (truck_station
) ? &st
->truck_stops
: &st
->bus_stops
;
1781 if (*primary_stop
== nullptr) {
1782 /* we have no roadstop of the type yet, so write a "primary stop" */
1783 return primary_stop
;
1785 /* there are stops already, so append to the end of the list */
1786 RoadStop
*stop
= *primary_stop
;
1787 while (stop
->next
!= nullptr) stop
= stop
->next
;
1792 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
);
1795 * Find a nearby station that joins this road stop.
1796 * @param existing_stop an existing road stop we build over
1797 * @param station_to_join the station to join to
1798 * @param adjacent whether adjacent stations are allowed
1799 * @param ta the area of the newly build station
1800 * @param st 'return' pointer for the found station
1801 * @return command cost with the error or 'okay'
1803 static CommandCost
FindJoiningRoadStop(StationID existing_stop
, StationID station_to_join
, bool adjacent
, TileArea ta
, Station
**st
)
1805 return FindJoiningBaseStation
<Station
, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST
>(existing_stop
, station_to_join
, adjacent
, ta
, st
);
1809 * Build a bus or truck stop.
1810 * @param tile Northernmost tile of the stop.
1811 * @param flags Operation to perform.
1812 * @param p1 bit 0..7: Width of the road stop.
1813 * bit 8..15: Length of the road stop.
1814 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
1815 * bit 1: 0 For normal stops, 1 for drive-through.
1816 * bit 2: Allow stations directly adjacent to other stations.
1817 * bit 3..4: Entrance direction (#DiagDirection) for normal stops.
1818 * bit 3: #Axis of the road for drive-through stops.
1819 * bit 5..10: The roadtype.
1820 * bit 16..31: Station ID to join (NEW_STATION if build new one).
1821 * @param text Unused.
1822 * @return The cost of this operation or an error.
1824 CommandCost
CmdBuildRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
1826 bool type
= HasBit(p2
, 0);
1827 bool is_drive_through
= HasBit(p2
, 1);
1828 RoadType rt
= Extract
<RoadType
, 5, 6>(p2
);
1829 if (!ValParamRoadType(rt
)) return CMD_ERROR
;
1830 StationID station_to_join
= GB(p2
, 16, 16);
1831 bool reuse
= (station_to_join
!= NEW_STATION
);
1832 if (!reuse
) station_to_join
= INVALID_STATION
;
1833 bool distant_join
= (station_to_join
!= INVALID_STATION
);
1835 uint8 width
= (uint8
)GB(p1
, 0, 8);
1836 uint8 length
= (uint8
)GB(p1
, 8, 8);
1838 /* Check if the requested road stop is too big */
1839 if (width
> _settings_game
.station
.station_spread
|| length
> _settings_game
.station
.station_spread
) return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
1840 /* Check for incorrect width / length. */
1841 if (width
== 0 || length
== 0) return CMD_ERROR
;
1842 /* Check if the first tile and the last tile are valid */
1843 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, length
- 1) == INVALID_TILE
) return CMD_ERROR
;
1845 TileArea
roadstop_area(tile
, width
, length
);
1847 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
1849 /* Trams only have drive through stops */
1850 if (!is_drive_through
&& RoadTypeIsTram(rt
)) return CMD_ERROR
;
1854 if (is_drive_through
) {
1855 /* By definition axis is valid, due to there being 2 axes and reading 1 bit. */
1856 axis
= Extract
<Axis
, 3, 1>(p2
);
1857 ddir
= AxisToDiagDir(axis
);
1859 /* By definition ddir is valid, due to there being 4 diagonal directions and reading 2 bits. */
1860 ddir
= Extract
<DiagDirection
, 3, 2>(p2
);
1861 axis
= DiagDirToAxis(ddir
);
1864 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
1865 if (ret
.Failed()) return ret
;
1867 /* Total road stop cost. */
1868 CommandCost
cost(EXPENSES_CONSTRUCTION
, roadstop_area
.w
* roadstop_area
.h
* _price
[type
? PR_BUILD_STATION_TRUCK
: PR_BUILD_STATION_BUS
]);
1869 StationID est
= INVALID_STATION
;
1870 ret
= CheckFlatLandRoadStop(roadstop_area
, flags
, is_drive_through
? 5 << axis
: 1 << ddir
, is_drive_through
, type
, axis
, &est
, rt
);
1871 if (ret
.Failed()) return ret
;
1874 Station
*st
= nullptr;
1875 ret
= FindJoiningRoadStop(est
, station_to_join
, HasBit(p2
, 2), roadstop_area
, &st
);
1876 if (ret
.Failed()) return ret
;
1878 /* Check if this number of road stops can be allocated. */
1879 if (!RoadStop::CanAllocateItem(roadstop_area
.w
* roadstop_area
.h
)) return_cmd_error(type
? STR_ERROR_TOO_MANY_TRUCK_STOPS
: STR_ERROR_TOO_MANY_BUS_STOPS
);
1881 ret
= BuildStationPart(&st
, flags
, reuse
, roadstop_area
, STATIONNAMING_ROAD
);
1882 if (ret
.Failed()) return ret
;
1884 if (flags
& DC_EXEC
) {
1885 /* Check every tile in the area. */
1886 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
1887 /* Get existing road types and owners before any tile clearing */
1888 RoadType road_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_ROAD
) : INVALID_ROADTYPE
;
1889 RoadType tram_rt
= MayHaveRoad(cur_tile
) ? GetRoadType(cur_tile
, RTT_TRAM
) : INVALID_ROADTYPE
;
1890 Owner road_owner
= road_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_ROAD
) : _current_company
;
1891 Owner tram_owner
= tram_rt
!= INVALID_ROADTYPE
? GetRoadOwner(cur_tile
, RTT_TRAM
) : _current_company
;
1893 if (IsTileType(cur_tile
, MP_STATION
) && IsRoadStop(cur_tile
)) {
1894 RemoveRoadStop(cur_tile
, flags
);
1897 RoadStop
*road_stop
= new RoadStop(cur_tile
);
1898 /* Insert into linked list of RoadStops. */
1899 RoadStop
**currstop
= FindRoadStopSpot(type
, st
);
1900 *currstop
= road_stop
;
1903 st
->truck_station
.Add(cur_tile
);
1905 st
->bus_station
.Add(cur_tile
);
1908 /* Initialize an empty station. */
1909 st
->AddFacility((type
) ? FACIL_TRUCK_STOP
: FACIL_BUS_STOP
, cur_tile
);
1911 st
->rect
.BeforeAddTile(cur_tile
, StationRect::ADD_TRY
);
1913 RoadStopType rs_type
= type
? ROADSTOP_TRUCK
: ROADSTOP_BUS
;
1914 if (is_drive_through
) {
1915 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
1917 if (IsNormalRoadTile(cur_tile
)) {
1918 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_ROAD
)));
1919 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, -(int)CountBits(GetRoadBits(cur_tile
, RTT_TRAM
)));
1922 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
1923 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
1925 UpdateCompanyRoadInfrastructure(road_rt
, road_owner
, 2);
1926 UpdateCompanyRoadInfrastructure(tram_rt
, tram_owner
, 2);
1928 MakeDriveThroughRoadStop(cur_tile
, st
->owner
, road_owner
, tram_owner
, st
->index
, rs_type
, road_rt
, tram_rt
, axis
);
1929 road_stop
->MakeDriveThrough();
1931 if (road_rt
== INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
)) road_rt
= rt
;
1932 if (tram_rt
== INVALID_ROADTYPE
&& RoadTypeIsTram(rt
)) tram_rt
= rt
;
1933 /* Non-drive-through stop never overbuild and always count as two road bits. */
1934 Company::Get(st
->owner
)->infrastructure
.road
[rt
] += 2;
1935 MakeRoadStop(cur_tile
, st
->owner
, st
->index
, rs_type
, road_rt
, tram_rt
, ddir
);
1937 Company::Get(st
->owner
)->infrastructure
.station
++;
1939 MarkTileDirtyByTile(cur_tile
);
1943 if (st
!= nullptr) {
1944 st
->AfterStationTileSetChange(true, type
? STATION_TRUCK
: STATION_BUS
);
1950 static Vehicle
*ClearRoadStopStatusEnum(Vehicle
*v
, void *)
1952 if (v
->type
== VEH_ROAD
) {
1953 /* Okay... we are a road vehicle on a drive through road stop.
1954 * But that road stop has just been removed, so we need to make
1955 * sure we are in a valid state... however, vehicles can also
1956 * turn on road stop tiles, so only clear the 'road stop' state
1957 * bits and only when the state was 'in road stop', otherwise
1958 * we'll end up clearing the turn around bits. */
1959 RoadVehicle
*rv
= RoadVehicle::From(v
);
1960 if (HasBit(rv
->state
, RVS_IN_DT_ROAD_STOP
)) rv
->state
&= RVSB_ROAD_STOP_TRACKDIR_MASK
;
1968 * Remove a bus station/truck stop
1969 * @param tile TileIndex been queried
1970 * @param flags operation to perform
1971 * @return cost or failure of operation
1973 static CommandCost
RemoveRoadStop(TileIndex tile
, DoCommandFlag flags
)
1975 Station
*st
= Station::GetByTile(tile
);
1977 if (_current_company
!= OWNER_WATER
) {
1978 CommandCost ret
= CheckOwnership(st
->owner
);
1979 if (ret
.Failed()) return ret
;
1982 bool is_truck
= IsTruckStop(tile
);
1984 RoadStop
**primary_stop
;
1986 if (is_truck
) { // truck stop
1987 primary_stop
= &st
->truck_stops
;
1988 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_TRUCK
);
1990 primary_stop
= &st
->bus_stops
;
1991 cur_stop
= RoadStop::GetByTile(tile
, ROADSTOP_BUS
);
1994 assert(cur_stop
!= nullptr);
1996 /* don't do the check for drive-through road stops when company bankrupts */
1997 if (IsDriveThroughStopTile(tile
) && (flags
& DC_BANKRUPT
)) {
1998 /* remove the 'going through road stop' status from all vehicles on that tile */
1999 if (flags
& DC_EXEC
) FindVehicleOnPos(tile
, nullptr, &ClearRoadStopStatusEnum
);
2001 CommandCost ret
= EnsureNoVehicleOnGround(tile
);
2002 if (ret
.Failed()) return ret
;
2005 if (flags
& DC_EXEC
) {
2006 if (*primary_stop
== cur_stop
) {
2007 /* removed the first stop in the list */
2008 *primary_stop
= cur_stop
->next
;
2009 /* removed the only stop? */
2010 if (*primary_stop
== nullptr) {
2011 st
->facilities
&= (is_truck
? ~FACIL_TRUCK_STOP
: ~FACIL_BUS_STOP
);
2014 /* tell the predecessor in the list to skip this stop */
2015 RoadStop
*pred
= *primary_stop
;
2016 while (pred
->next
!= cur_stop
) pred
= pred
->next
;
2017 pred
->next
= cur_stop
->next
;
2020 /* Update company infrastructure counts. */
2021 FOR_ALL_ROADTRAMTYPES(rtt
) {
2022 RoadType rt
= GetRoadType(tile
, rtt
);
2023 UpdateCompanyRoadInfrastructure(rt
, GetRoadOwner(tile
, rtt
), -2);
2026 Company::Get(st
->owner
)->infrastructure
.station
--;
2027 DirtyCompanyInfrastructureWindows(st
->owner
);
2029 if (IsDriveThroughStopTile(tile
)) {
2030 /* Clears the tile for us */
2031 cur_stop
->ClearDriveThrough();
2033 DoClearSquare(tile
);
2038 /* Make sure no vehicle is going to the old roadstop */
2040 FOR_ALL_ROADVEHICLES(v
) {
2041 if (v
->First() == v
&& v
->current_order
.IsType(OT_GOTO_STATION
) &&
2042 v
->dest_tile
== tile
) {
2043 v
->SetDestTile(v
->GetOrderStationLocation(st
->index
));
2047 st
->rect
.AfterRemoveTile(st
, tile
);
2049 st
->AfterStationTileSetChange(false, is_truck
? STATION_TRUCK
: STATION_BUS
);
2051 /* Update the tile area of the truck/bus stop */
2053 st
->truck_station
.Clear();
2054 for (const RoadStop
*rs
= st
->truck_stops
; rs
!= nullptr; rs
= rs
->next
) st
->truck_station
.Add(rs
->xy
);
2056 st
->bus_station
.Clear();
2057 for (const RoadStop
*rs
= st
->bus_stops
; rs
!= nullptr; rs
= rs
->next
) st
->bus_station
.Add(rs
->xy
);
2061 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[is_truck
? PR_CLEAR_STATION_TRUCK
: PR_CLEAR_STATION_BUS
]);
2065 * Remove bus or truck stops.
2066 * @param tile Northernmost tile of the removal area.
2067 * @param flags Operation to perform.
2068 * @param p1 bit 0..7: Width of the removal area.
2069 * bit 8..15: Height of the removal area.
2070 * @param p2 bit 0: 0 For bus stops, 1 for truck stops.
2071 * @param p2 bit 1: 0 to keep roads of all drive-through stops, 1 to remove them.
2072 * @param text Unused.
2073 * @return The cost of this operation or an error.
2075 CommandCost
CmdRemoveRoadStop(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2077 uint8 width
= (uint8
)GB(p1
, 0, 8);
2078 uint8 height
= (uint8
)GB(p1
, 8, 8);
2079 bool keep_drive_through_roads
= !HasBit(p2
, 1);
2081 /* Check for incorrect width / height. */
2082 if (width
== 0 || height
== 0) return CMD_ERROR
;
2083 /* Check if the first tile and the last tile are valid */
2084 if (!IsValidTile(tile
) || TileAddWrap(tile
, width
- 1, height
- 1) == INVALID_TILE
) return CMD_ERROR
;
2085 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2086 if (!keep_drive_through_roads
&& (flags
& DC_BANKRUPT
)) return CMD_ERROR
;
2088 TileArea
roadstop_area(tile
, width
, height
);
2090 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2091 CommandCost
last_error(STR_ERROR_THERE_IS_NO_STATION
);
2092 bool had_success
= false;
2094 TILE_AREA_LOOP(cur_tile
, roadstop_area
) {
2095 /* Make sure the specified tile is a road stop of the correct type */
2096 if (!IsTileType(cur_tile
, MP_STATION
) || !IsRoadStop(cur_tile
) || (uint32
)GetRoadStopType(cur_tile
) != GB(p2
, 0, 1)) continue;
2098 /* Save information on to-be-restored roads before the stop is removed. */
2099 RoadBits road_bits
= ROAD_NONE
;
2100 RoadType road_type
[] = { INVALID_ROADTYPE
, INVALID_ROADTYPE
};
2101 Owner road_owner
[] = { OWNER_NONE
, OWNER_NONE
};
2102 if (IsDriveThroughStopTile(cur_tile
)) {
2103 FOR_ALL_ROADTRAMTYPES(rtt
) {
2104 road_type
[rtt
] = GetRoadType(cur_tile
, rtt
);
2105 if (road_type
[rtt
] == INVALID_ROADTYPE
) continue;
2106 road_owner
[rtt
] = GetRoadOwner(cur_tile
, rtt
);
2107 /* If we don't want to preserve our roads then restore only roads of others. */
2108 if (!keep_drive_through_roads
&& road_owner
[rtt
] == _current_company
) road_type
[rtt
] = INVALID_ROADTYPE
;
2110 road_bits
= AxisToRoadBits(DiagDirToAxis(GetRoadStopDir(cur_tile
)));
2113 CommandCost ret
= RemoveRoadStop(cur_tile
, flags
);
2121 /* Restore roads. */
2122 if ((flags
& DC_EXEC
) && (road_type
[RTT_ROAD
] != INVALID_ROADTYPE
|| road_type
[RTT_TRAM
] != INVALID_ROADTYPE
)) {
2123 MakeRoadNormal(cur_tile
, road_bits
, road_type
[RTT_ROAD
], road_type
[RTT_TRAM
], ClosestTownFromTile(cur_tile
, UINT_MAX
)->index
,
2124 road_owner
[RTT_ROAD
], road_owner
[RTT_TRAM
]);
2126 /* Update company infrastructure counts. */
2127 int count
= CountBits(road_bits
);
2128 UpdateCompanyRoadInfrastructure(road_type
[RTT_ROAD
], road_owner
[RTT_ROAD
], count
);
2129 UpdateCompanyRoadInfrastructure(road_type
[RTT_TRAM
], road_owner
[RTT_TRAM
], count
);
2133 return had_success
? cost
: last_error
;
2137 * Computes the minimal distance from town's xy to any airport's tile.
2138 * @param it An iterator over all airport tiles.
2139 * @param town_tile town's tile (t->xy)
2140 * @return minimal manhattan distance from town_tile to any airport's tile
2142 static uint
GetMinimalAirportDistanceToTile(TileIterator
&it
, TileIndex town_tile
)
2144 uint mindist
= UINT_MAX
;
2146 for (TileIndex cur_tile
= it
; cur_tile
!= INVALID_TILE
; cur_tile
= ++it
) {
2147 mindist
= min(mindist
, DistanceManhattan(town_tile
, cur_tile
));
2154 * Get a possible noise reduction factor based on distance from town center.
2155 * The further you get, the less noise you generate.
2156 * So all those folks at city council can now happily slee... work in their offices
2157 * @param as airport information
2158 * @param distance minimum distance between town and airport
2159 * @return the noise that will be generated, according to distance
2161 uint8
GetAirportNoiseLevelForDistance(const AirportSpec
*as
, uint distance
)
2163 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2164 * So no need to go any further*/
2165 if (as
->noise_level
< 2) return as
->noise_level
;
2167 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2168 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2169 * Basically, it says that the less tolerant a town is, the bigger the distance before
2170 * an actual decrease can be granted */
2171 uint8 town_tolerance_distance
= 8 + (_settings_game
.difficulty
.town_council_tolerance
* 4);
2173 /* now, we want to have the distance segmented using the distance judged bareable by town
2174 * This will give us the coefficient of reduction the distance provides. */
2175 uint noise_reduction
= distance
/ town_tolerance_distance
;
2177 /* If the noise reduction equals the airport noise itself, don't give it for free.
2178 * Otherwise, simply reduce the airport's level. */
2179 return noise_reduction
>= as
->noise_level
? 1 : as
->noise_level
- noise_reduction
;
2183 * Finds the town nearest to given airport. Based on minimal manhattan distance to any airport's tile.
2184 * If two towns have the same distance, town with lower index is returned.
2185 * @param as airport's description
2186 * @param it An iterator over all airport tiles
2187 * @param[out] mindist Minimum distance to town
2188 * @return nearest town to airport
2190 Town
*AirportGetNearestTown(const AirportSpec
*as
, const TileIterator
&it
, uint
&mindist
)
2192 Town
*t
, *nearest
= nullptr;
2193 uint add
= as
->size_x
+ as
->size_y
- 2; // GetMinimalAirportDistanceToTile can differ from DistanceManhattan by this much
2194 mindist
= UINT_MAX
- add
; // prevent overflow
2196 if (DistanceManhattan(t
->xy
, it
) < mindist
+ add
) { // avoid calling GetMinimalAirportDistanceToTile too often
2197 TileIterator
*copy
= it
.Clone();
2198 uint dist
= GetMinimalAirportDistanceToTile(*copy
, t
->xy
);
2200 if (dist
< mindist
) {
2211 /** Recalculate the noise generated by the airports of each town */
2212 void UpdateAirportsNoise()
2217 FOR_ALL_TOWNS(t
) t
->noise_reached
= 0;
2219 FOR_ALL_STATIONS(st
) {
2220 if (st
->airport
.tile
!= INVALID_TILE
&& st
->airport
.type
!= AT_OILRIG
) {
2221 const AirportSpec
*as
= st
->airport
.GetSpec();
2222 AirportTileIterator
it(st
);
2224 Town
*nearest
= AirportGetNearestTown(as
, it
, dist
);
2225 nearest
->noise_reached
+= GetAirportNoiseLevelForDistance(as
, dist
);
2232 * @param tile tile where airport will be built
2233 * @param flags operation to perform
2235 * - p1 = (bit 0- 7) - airport type, @see airport.h
2236 * - p1 = (bit 8-15) - airport layout
2237 * @param p2 various bitstuffed elements
2238 * - p2 = (bit 0) - allow airports directly adjacent to other airports.
2239 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
2240 * @param text unused
2241 * @return the cost of this operation or an error
2243 CommandCost
CmdBuildAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2245 StationID station_to_join
= GB(p2
, 16, 16);
2246 bool reuse
= (station_to_join
!= NEW_STATION
);
2247 if (!reuse
) station_to_join
= INVALID_STATION
;
2248 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2249 byte airport_type
= GB(p1
, 0, 8);
2250 byte layout
= GB(p1
, 8, 8);
2252 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2254 if (airport_type
>= NUM_AIRPORTS
) return CMD_ERROR
;
2256 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2257 if (ret
.Failed()) return ret
;
2259 /* Check if a valid, buildable airport was chosen for construction */
2260 const AirportSpec
*as
= AirportSpec::Get(airport_type
);
2261 if (!as
->IsAvailable() || layout
>= as
->num_table
) return CMD_ERROR
;
2262 if (!as
->IsWithinMapBounds(layout
, tile
)) return CMD_ERROR
;
2264 Direction rotation
= as
->rotation
[layout
];
2267 if (rotation
== DIR_E
|| rotation
== DIR_W
) Swap(w
, h
);
2268 TileArea airport_area
= TileArea(tile
, w
, h
);
2270 if (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
) {
2271 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
2274 AirportTileTableIterator
iter(as
->table
[layout
], tile
);
2275 CommandCost cost
= CheckFlatLandAirport(iter
, flags
);
2276 if (cost
.Failed()) return cost
;
2278 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2280 Town
*nearest
= AirportGetNearestTown(as
, iter
, dist
);
2281 uint newnoise_level
= GetAirportNoiseLevelForDistance(as
, dist
);
2283 /* Check if local auth would allow a new airport */
2284 StringID authority_refuse_message
= STR_NULL
;
2285 Town
*authority_refuse_town
= nullptr;
2287 if (_settings_game
.economy
.station_noise_level
) {
2288 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2289 if ((nearest
->noise_reached
+ newnoise_level
) > nearest
->MaxTownNoise()) {
2290 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE
;
2291 authority_refuse_town
= nearest
;
2294 Town
*t
= ClosestTownFromTile(tile
, UINT_MAX
);
2297 FOR_ALL_STATIONS(st
) {
2298 if (st
->town
== t
&& (st
->facilities
& FACIL_AIRPORT
) && st
->airport
.type
!= AT_OILRIG
) num
++;
2301 authority_refuse_message
= STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT
;
2302 authority_refuse_town
= t
;
2306 if (authority_refuse_message
!= STR_NULL
) {
2307 SetDParam(0, authority_refuse_town
->index
);
2308 return_cmd_error(authority_refuse_message
);
2311 Station
*st
= nullptr;
2312 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p2
, 0), airport_area
, &st
);
2313 if (ret
.Failed()) return ret
;
2316 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2318 ret
= BuildStationPart(&st
, flags
, reuse
, airport_area
, (GetAirport(airport_type
)->flags
& AirportFTAClass::AIRPLANES
) ? STATIONNAMING_AIRPORT
: STATIONNAMING_HELIPORT
);
2319 if (ret
.Failed()) return ret
;
2321 if (st
!= nullptr && st
->airport
.tile
!= INVALID_TILE
) {
2322 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT
);
2325 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2326 cost
.AddCost(_price
[PR_BUILD_STATION_AIRPORT
]);
2329 if (flags
& DC_EXEC
) {
2330 /* Always add the noise, so there will be no need to recalculate when option toggles */
2331 nearest
->noise_reached
+= newnoise_level
;
2333 st
->AddFacility(FACIL_AIRPORT
, tile
);
2334 st
->airport
.type
= airport_type
;
2335 st
->airport
.layout
= layout
;
2336 st
->airport
.flags
= 0;
2337 st
->airport
.rotation
= rotation
;
2339 st
->rect
.BeforeAddRect(tile
, w
, h
, StationRect::ADD_TRY
);
2341 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2342 MakeAirport(iter
, st
->owner
, st
->index
, iter
.GetStationGfx(), WATER_CLASS_INVALID
);
2343 SetStationTileRandomBits(iter
, GB(Random(), 0, 4));
2344 st
->airport
.Add(iter
);
2346 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter
.GetStationGfx()))->animation
.status
!= ANIM_STATUS_NO_ANIMATION
) AddAnimatedTile(iter
);
2349 /* Only call the animation trigger after all tiles have been built */
2350 for (AirportTileTableIterator
iter(as
->table
[layout
], tile
); iter
!= INVALID_TILE
; ++iter
) {
2351 AirportTileAnimationTrigger(st
, iter
, AAT_BUILT
);
2354 UpdateAirplanesOnNewStation(st
);
2356 Company::Get(st
->owner
)->infrastructure
.airport
++;
2358 st
->AfterStationTileSetChange(true, STATION_AIRPORT
);
2359 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2361 if (_settings_game
.economy
.station_noise_level
) {
2362 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2371 * @param tile TileIndex been queried
2372 * @param flags operation to perform
2373 * @return cost or failure of operation
2375 static CommandCost
RemoveAirport(TileIndex tile
, DoCommandFlag flags
)
2377 Station
*st
= Station::GetByTile(tile
);
2379 if (_current_company
!= OWNER_WATER
) {
2380 CommandCost ret
= CheckOwnership(st
->owner
);
2381 if (ret
.Failed()) return ret
;
2384 tile
= st
->airport
.tile
;
2386 CommandCost
cost(EXPENSES_CONSTRUCTION
);
2389 FOR_ALL_AIRCRAFT(a
) {
2390 if (!a
->IsNormalAircraft()) continue;
2391 if (a
->targetairport
== st
->index
&& a
->state
!= FLYING
) {
2392 return_cmd_error(STR_ERROR_AIRCRAFT_IN_THE_WAY
);
2396 if (flags
& DC_EXEC
) {
2397 const AirportSpec
*as
= st
->airport
.GetSpec();
2398 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2399 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2400 * need of recalculation */
2401 AirportTileIterator
it(st
);
2403 Town
*nearest
= AirportGetNearestTown(as
, it
, dist
);
2404 nearest
->noise_reached
-= GetAirportNoiseLevelForDistance(as
, dist
);
2407 TILE_AREA_LOOP(tile_cur
, st
->airport
) {
2408 if (!st
->TileBelongsToAirport(tile_cur
)) continue;
2410 CommandCost ret
= EnsureNoVehicleOnGround(tile_cur
);
2411 if (ret
.Failed()) return ret
;
2413 cost
.AddCost(_price
[PR_CLEAR_STATION_AIRPORT
]);
2415 if (flags
& DC_EXEC
) {
2416 if (IsHangarTile(tile_cur
)) OrderBackup::Reset(tile_cur
, false);
2417 DeleteAnimatedTile(tile_cur
);
2418 DoClearSquare(tile_cur
);
2419 DeleteNewGRFInspectWindow(GSF_AIRPORTTILES
, tile_cur
);
2423 if (flags
& DC_EXEC
) {
2424 /* Clear the persistent storage. */
2425 delete st
->airport
.psa
;
2427 for (uint i
= 0; i
< st
->airport
.GetNumHangars(); ++i
) {
2429 WC_VEHICLE_DEPOT
, st
->airport
.GetHangarTile(i
)
2433 st
->rect
.AfterRemoveRect(st
, st
->airport
);
2435 st
->airport
.Clear();
2436 st
->facilities
&= ~FACIL_AIRPORT
;
2438 InvalidateWindowData(WC_STATION_VIEW
, st
->index
, -1);
2440 if (_settings_game
.economy
.station_noise_level
) {
2441 SetWindowDirty(WC_TOWN_VIEW
, st
->town
->index
);
2444 Company::Get(st
->owner
)->infrastructure
.airport
--;
2446 st
->AfterStationTileSetChange(false, STATION_AIRPORT
);
2448 DeleteNewGRFInspectWindow(GSF_AIRPORTS
, st
->index
);
2455 * Open/close an airport to incoming aircraft.
2456 * @param tile Unused.
2457 * @param flags Operation to perform.
2458 * @param p1 Station ID of the airport.
2460 * @param text unused
2461 * @return the cost of this operation or an error
2463 CommandCost
CmdOpenCloseAirport(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2465 if (!Station::IsValidID(p1
)) return CMD_ERROR
;
2466 Station
*st
= Station::Get(p1
);
2468 if (!(st
->facilities
& FACIL_AIRPORT
) || st
->owner
== OWNER_NONE
) return CMD_ERROR
;
2470 CommandCost ret
= CheckOwnership(st
->owner
);
2471 if (ret
.Failed()) return ret
;
2473 if (flags
& DC_EXEC
) {
2474 st
->airport
.flags
^= AIRPORT_CLOSED_block
;
2475 SetWindowWidgetDirty(WC_STATION_VIEW
, st
->index
, WID_SV_CLOSE_AIRPORT
);
2477 return CommandCost();
2481 * Tests whether the company's vehicles have this station in orders
2482 * @param station station ID
2483 * @param include_company If true only check vehicles of \a company, if false only check vehicles of other companies
2484 * @param company company ID
2486 bool HasStationInUse(StationID station
, bool include_company
, CompanyID company
)
2489 FOR_ALL_VEHICLES(v
) {
2490 if ((v
->owner
== company
) == include_company
) {
2492 FOR_VEHICLE_ORDERS(v
, order
) {
2493 if ((order
->IsType(OT_GOTO_STATION
) || order
->IsType(OT_GOTO_WAYPOINT
)) && order
->GetDestination() == station
) {
2502 static const TileIndexDiffC _dock_tileoffs_chkaround
[] = {
2508 static const byte _dock_w_chk
[4] = { 2, 1, 2, 1 };
2509 static const byte _dock_h_chk
[4] = { 1, 2, 1, 2 };
2512 * Build a dock/haven.
2513 * @param tile tile where dock will be built
2514 * @param flags operation to perform
2515 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
2516 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
2517 * @param text unused
2518 * @return the cost of this operation or an error
2520 CommandCost
CmdBuildDock(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
2522 StationID station_to_join
= GB(p2
, 16, 16);
2523 bool reuse
= (station_to_join
!= NEW_STATION
);
2524 if (!reuse
) station_to_join
= INVALID_STATION
;
2525 bool distant_join
= (station_to_join
!= INVALID_STATION
);
2527 if (distant_join
&& (!_settings_game
.station
.distant_join_stations
|| !Station::IsValidID(station_to_join
))) return CMD_ERROR
;
2529 DiagDirection direction
= GetInclinedSlopeDirection(GetTileSlope(tile
));
2530 if (direction
== INVALID_DIAGDIR
) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2531 direction
= ReverseDiagDir(direction
);
2533 /* Docks cannot be placed on rapids */
2534 if (HasTileWaterGround(tile
)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2536 CommandCost ret
= CheckIfAuthorityAllowsNewStation(tile
, flags
);
2537 if (ret
.Failed()) return ret
;
2539 if (IsBridgeAbove(tile
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2541 ret
= DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2542 if (ret
.Failed()) return ret
;
2544 TileIndex tile_cur
= tile
+ TileOffsByDiagDir(direction
);
2546 if (!IsTileType(tile_cur
, MP_WATER
) || !IsTileFlat(tile_cur
)) {
2547 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2550 if (IsBridgeAbove(tile_cur
)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
2552 /* Get the water class of the water tile before it is cleared.*/
2553 WaterClass wc
= GetWaterClass(tile_cur
);
2555 ret
= DoCommand(tile_cur
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
2556 if (ret
.Failed()) return ret
;
2558 tile_cur
+= TileOffsByDiagDir(direction
);
2559 if (!IsTileType(tile_cur
, MP_WATER
) || !IsTileFlat(tile_cur
)) {
2560 return_cmd_error(STR_ERROR_SITE_UNSUITABLE
);
2563 TileArea dock_area
= TileArea(tile
+ ToTileIndexDiff(_dock_tileoffs_chkaround
[direction
]),
2564 _dock_w_chk
[direction
], _dock_h_chk
[direction
]);
2567 Station
*st
= nullptr;
2568 ret
= FindJoiningStation(INVALID_STATION
, station_to_join
, HasBit(p1
, 0), dock_area
, &st
);
2569 if (ret
.Failed()) return ret
;
2572 if (st
== nullptr && distant_join
) st
= Station::GetIfValid(station_to_join
);
2574 ret
= BuildStationPart(&st
, flags
, reuse
, dock_area
, STATIONNAMING_DOCK
);
2575 if (ret
.Failed()) return ret
;
2577 if (flags
& DC_EXEC
) {
2578 st
->ship_station
.Add(tile
);
2579 st
->ship_station
.Add(tile
+ TileOffsByDiagDir(direction
));
2580 st
->AddFacility(FACIL_DOCK
, tile
);
2582 st
->rect
.BeforeAddRect(dock_area
.tile
, dock_area
.w
, dock_area
.h
, StationRect::ADD_TRY
);
2584 /* If the water part of the dock is on a canal, update infrastructure counts.
2585 * This is needed as we've unconditionally cleared that tile before. */
2586 if (wc
== WATER_CLASS_CANAL
) {
2587 Company::Get(st
->owner
)->infrastructure
.water
++;
2589 Company::Get(st
->owner
)->infrastructure
.station
+= 2;
2591 MakeDock(tile
, st
->owner
, st
->index
, direction
, wc
);
2592 UpdateStationDockingTiles(st
);
2594 st
->AfterStationTileSetChange(true, STATION_DOCK
);
2597 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_STATION_DOCK
]);
2600 void RemoveDockingTile(TileIndex t
)
2602 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2603 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2604 if (!IsValidTile(tile
)) continue;
2606 if (IsTileType(tile
, MP_STATION
)) {
2607 UpdateStationDockingTiles(Station::GetByTile(tile
));
2608 } else if (IsTileType(tile
, MP_INDUSTRY
)) {
2609 Station
*neutral
= Industry::GetByTile(tile
)->neutral_station
;
2610 if (neutral
!= nullptr) UpdateStationDockingTiles(neutral
);
2616 * Clear docking tile status from tiles around a removed dock, if the tile has
2617 * no neighbours which would keep it as a docking tile.
2618 * @param tile Ex-dock tile to check.
2620 void ClearDockingTilesCheckingNeighbours(TileIndex tile
)
2622 assert(IsValidTile(tile
));
2624 /* Clear and maybe re-set docking tile */
2625 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2626 TileIndex docking_tile
= tile
+ TileOffsByDiagDir(d
);
2627 if (!IsValidTile(docking_tile
)) continue;
2629 if (IsPossibleDockingTile(docking_tile
)) {
2630 SetDockingTile(docking_tile
, false);
2631 CheckForDockingTile(docking_tile
);
2637 * Check if a dock tile can be docked from the given direction.
2638 * @param t Tile index of dock.
2639 * @param d DiagDirection adjacent to dock being tested.
2640 * @return True iff the dock can be docked from the given direction.
2642 bool IsValidDockingDirectionForDock(TileIndex t
, DiagDirection d
)
2644 assert(IsDockTile(t
));
2646 /** Bitmap of valid directions for each dock tile part. */
2647 static const uint8 _valid_docking_tile
[] = {
2648 0, 0, 0, 0, // No docking against the slope part.
2649 1 << DIAGDIR_NE
| 1 << DIAGDIR_SW
, // Docking permitted at the end
2650 1 << DIAGDIR_NW
| 1 << DIAGDIR_SE
, // of the flat piers.
2653 StationGfx gfx
= GetStationGfx(t
);
2654 assert(gfx
< lengthof(_valid_docking_tile
));
2655 return HasBit(_valid_docking_tile
[gfx
], d
);
2659 * Find the part of a dock that is land-based
2660 * @param t Dock tile to find land part of
2661 * @return tile of land part of dock
2663 static TileIndex
FindDockLandPart(TileIndex t
)
2665 assert(IsDockTile(t
));
2667 StationGfx gfx
= GetStationGfx(t
);
2668 if (gfx
< GFX_DOCK_BASE_WATER_PART
) return t
;
2670 for (DiagDirection d
= DIAGDIR_BEGIN
; d
!= DIAGDIR_END
; d
++) {
2671 TileIndex tile
= t
+ TileOffsByDiagDir(d
);
2672 if (!IsValidTile(tile
)) continue;
2673 if (!IsDockTile(tile
)) continue;
2674 if (GetStationGfx(tile
) < GFX_DOCK_BASE_WATER_PART
&& tile
+ TileOffsByDiagDir(GetDockDirection(tile
)) == t
) return tile
;
2677 return INVALID_TILE
;
2682 * @param tile TileIndex been queried
2683 * @param flags operation to perform
2684 * @return cost or failure of operation
2686 static CommandCost
RemoveDock(TileIndex tile
, DoCommandFlag flags
)
2688 Station
*st
= Station::GetByTile(tile
);
2689 CommandCost ret
= CheckOwnership(st
->owner
);
2690 if (ret
.Failed()) return ret
;
2692 if (!IsDockTile(tile
)) return CMD_ERROR
;
2694 TileIndex tile1
= FindDockLandPart(tile
);
2695 if (tile1
== INVALID_TILE
) return CMD_ERROR
;
2696 TileIndex tile2
= tile1
+ TileOffsByDiagDir(GetDockDirection(tile1
));
2698 ret
= EnsureNoVehicleOnGround(tile1
);
2699 if (ret
.Succeeded()) ret
= EnsureNoVehicleOnGround(tile2
);
2700 if (ret
.Failed()) return ret
;
2702 if (flags
& DC_EXEC
) {
2703 DoClearSquare(tile1
);
2704 MarkTileDirtyByTile(tile1
);
2705 MakeWaterKeepingClass(tile2
, st
->owner
);
2707 st
->rect
.AfterRemoveTile(st
, tile1
);
2708 st
->rect
.AfterRemoveTile(st
, tile2
);
2710 MakeShipStationAreaSmaller(st
);
2711 if (st
->ship_station
.tile
== INVALID_TILE
) {
2712 st
->ship_station
.Clear();
2713 st
->docking_station
.Clear();
2714 st
->facilities
&= ~FACIL_DOCK
;
2717 Company::Get(st
->owner
)->infrastructure
.station
-= 2;
2719 st
->AfterStationTileSetChange(false, STATION_DOCK
);
2721 ClearDockingTilesCheckingNeighbours(tile1
);
2722 ClearDockingTilesCheckingNeighbours(tile2
);
2724 /* All ships that were going to our station, can't go to it anymore.
2725 * Just clear the order, then automatically the next appropriate order
2726 * will be selected and in case of no appropriate order it will just
2727 * wander around the world. */
2728 if (!(st
->facilities
& FACIL_DOCK
)) {
2731 if (s
->current_order
.IsType(OT_LOADING
) && s
->current_order
.GetDestination() == st
->index
) {
2735 if (s
->current_order
.IsType(OT_GOTO_STATION
) && s
->current_order
.GetDestination() == st
->index
) {
2736 s
->SetDestTile(s
->GetOrderStationLocation(st
->index
));
2742 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_CLEAR_STATION_DOCK
]);
2745 #include "table/station_land.h"
2747 const DrawTileSprites
*GetStationTileLayout(StationType st
, byte gfx
)
2749 return &_station_display_datas
[st
][gfx
];
2753 * Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a rail overlay.
2754 * If the ground sprite is suitable, \a ground is replaced with the new non-track ground sprite, and \a overlay_offset
2755 * is set to the overlay to draw.
2756 * @param ti Positional info for the tile to decide snowyness etc. May be nullptr.
2757 * @param[in,out] ground Groundsprite to draw.
2758 * @param[out] overlay_offset Overlay to draw.
2759 * @return true if overlay can be drawn.
2761 bool SplitGroundSpriteForOverlay(const TileInfo
*ti
, SpriteID
*ground
, RailTrackOffset
*overlay_offset
)
2765 case SPR_RAIL_TRACK_X
:
2766 case SPR_MONO_TRACK_X
:
2767 case SPR_MGLV_TRACK_X
:
2768 snow_desert
= false;
2769 *overlay_offset
= RTO_X
;
2772 case SPR_RAIL_TRACK_Y
:
2773 case SPR_MONO_TRACK_Y
:
2774 case SPR_MGLV_TRACK_Y
:
2775 snow_desert
= false;
2776 *overlay_offset
= RTO_Y
;
2779 case SPR_RAIL_TRACK_X_SNOW
:
2780 case SPR_MONO_TRACK_X_SNOW
:
2781 case SPR_MGLV_TRACK_X_SNOW
:
2783 *overlay_offset
= RTO_X
;
2786 case SPR_RAIL_TRACK_Y_SNOW
:
2787 case SPR_MONO_TRACK_Y_SNOW
:
2788 case SPR_MGLV_TRACK_Y_SNOW
:
2790 *overlay_offset
= RTO_Y
;
2797 if (ti
!= nullptr) {
2798 /* Decide snow/desert from tile */
2799 switch (_settings_game
.game_creation
.landscape
) {
2801 snow_desert
= (uint
)ti
->z
> GetSnowLine() * TILE_HEIGHT
;
2805 snow_desert
= GetTropicZone(ti
->tile
) == TROPICZONE_DESERT
;
2813 *ground
= snow_desert
? SPR_FLAT_SNOW_DESERT_TILE
: SPR_FLAT_GRASS_TILE
;
2817 static void DrawTile_Station(TileInfo
*ti
)
2819 const NewGRFSpriteLayout
*layout
= nullptr;
2820 DrawTileSprites tmp_rail_layout
;
2821 const DrawTileSprites
*t
= nullptr;
2823 const RailtypeInfo
*rti
= nullptr;
2824 uint32 relocation
= 0;
2825 uint32 ground_relocation
= 0;
2826 BaseStation
*st
= nullptr;
2827 const StationSpec
*statspec
= nullptr;
2828 uint tile_layout
= 0;
2830 if (HasStationRail(ti
->tile
)) {
2831 rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
2832 total_offset
= rti
->GetRailtypeSpriteOffset();
2834 if (IsCustomStationSpecIndex(ti
->tile
)) {
2835 /* look for customization */
2836 st
= BaseStation::GetByTile(ti
->tile
);
2837 statspec
= st
->speclist
[GetCustomStationSpecIndex(ti
->tile
)].spec
;
2839 if (statspec
!= nullptr) {
2840 tile_layout
= GetStationGfx(ti
->tile
);
2842 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
2843 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, st
, ti
->tile
);
2844 if (callback
!= CALLBACK_FAILED
) tile_layout
= (callback
& ~1) + GetRailStationAxis(ti
->tile
);
2847 /* Ensure the chosen tile layout is valid for this custom station */
2848 if (statspec
->renderdata
!= nullptr) {
2849 layout
= &statspec
->renderdata
[tile_layout
< statspec
->tiles
? tile_layout
: (uint
)GetRailStationAxis(ti
->tile
)];
2850 if (!layout
->NeedsPreprocessing()) {
2861 StationGfx gfx
= GetStationGfx(ti
->tile
);
2862 if (IsAirport(ti
->tile
)) {
2863 gfx
= GetAirportGfx(ti
->tile
);
2864 if (gfx
>= NEW_AIRPORTTILE_OFFSET
) {
2865 const AirportTileSpec
*ats
= AirportTileSpec::Get(gfx
);
2866 if (ats
->grf_prop
.spritegroup
[0] != nullptr && DrawNewAirportTile(ti
, Station::GetByTile(ti
->tile
), gfx
, ats
)) {
2869 /* No sprite group (or no valid one) found, meaning no graphics associated.
2870 * Use the substitute one instead */
2871 assert(ats
->grf_prop
.subst_id
!= INVALID_AIRPORTTILE
);
2872 gfx
= ats
->grf_prop
.subst_id
;
2875 case APT_RADAR_GRASS_FENCE_SW
:
2876 t
= &_station_display_datas_airport_radar_grass_fence_sw
[GetAnimationFrame(ti
->tile
)];
2878 case APT_GRASS_FENCE_NE_FLAG
:
2879 t
= &_station_display_datas_airport_flag_grass_fence_ne
[GetAnimationFrame(ti
->tile
)];
2881 case APT_RADAR_FENCE_SW
:
2882 t
= &_station_display_datas_airport_radar_fence_sw
[GetAnimationFrame(ti
->tile
)];
2884 case APT_RADAR_FENCE_NE
:
2885 t
= &_station_display_datas_airport_radar_fence_ne
[GetAnimationFrame(ti
->tile
)];
2887 case APT_GRASS_FENCE_NE_FLAG_2
:
2888 t
= &_station_display_datas_airport_flag_grass_fence_ne_2
[GetAnimationFrame(ti
->tile
)];
2893 Owner owner
= GetTileOwner(ti
->tile
);
2896 if (Company::IsValidID(owner
)) {
2897 palette
= COMPANY_SPRITE_COLOUR(owner
);
2899 /* Some stations are not owner by a company, namely oil rigs */
2900 palette
= PALETTE_TO_GREY
;
2903 if (layout
== nullptr && (t
== nullptr || t
->seq
== nullptr)) t
= GetStationTileLayout(GetStationType(ti
->tile
), gfx
);
2905 /* don't show foundation for docks */
2906 if (ti
->tileh
!= SLOPE_FLAT
&& !IsDock(ti
->tile
)) {
2907 if (statspec
!= nullptr && HasBit(statspec
->flags
, SSF_CUSTOM_FOUNDATIONS
)) {
2908 /* Station has custom foundations.
2909 * Check whether the foundation continues beyond the tile's upper sides. */
2912 Slope slope
= GetFoundationPixelSlope(ti
->tile
, &z
);
2913 if (!HasFoundationNW(ti
->tile
, slope
, z
)) SetBit(edge_info
, 0);
2914 if (!HasFoundationNE(ti
->tile
, slope
, z
)) SetBit(edge_info
, 1);
2915 SpriteID image
= GetCustomStationFoundationRelocation(statspec
, st
, ti
->tile
, tile_layout
, edge_info
);
2916 if (image
== 0) goto draw_default_foundation
;
2918 if (HasBit(statspec
->flags
, SSF_EXTENDED_FOUNDATIONS
)) {
2919 /* Station provides extended foundations. */
2921 static const uint8 foundation_parts
[] = {
2922 0, 0, 0, 0, // Invalid, Invalid, Invalid, SLOPE_SW
2923 0, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
2924 0, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
2925 7, 8, 9 // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
2928 AddSortableSpriteToDraw(image
+ foundation_parts
[ti
->tileh
], PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2930 /* Draw simple foundations, built up from 8 possible foundation sprites. */
2932 /* Each set bit represents one of the eight composite sprites to be drawn.
2933 * 'Invalid' entries will not drawn but are included for completeness. */
2934 static const uint8 composite_foundation_parts
[] = {
2935 /* Invalid (00000000), Invalid (11010001), Invalid (11100100), SLOPE_SW (11100000) */
2936 0x00, 0xD1, 0xE4, 0xE0,
2937 /* Invalid (11001010), SLOPE_EW (11001001), SLOPE_SE (11000100), SLOPE_WSE (11000000) */
2938 0xCA, 0xC9, 0xC4, 0xC0,
2939 /* Invalid (11010010), SLOPE_NW (10010001), SLOPE_NS (11100100), SLOPE_NWS (10100000) */
2940 0xD2, 0x91, 0xE4, 0xA0,
2941 /* SLOPE_NE (01001010), SLOPE_ENW (00001001), SLOPE_SEN (01000100) */
2945 uint8 parts
= composite_foundation_parts
[ti
->tileh
];
2947 /* If foundations continue beyond the tile's upper sides then
2948 * mask out the last two pieces. */
2949 if (HasBit(edge_info
, 0)) ClrBit(parts
, 6);
2950 if (HasBit(edge_info
, 1)) ClrBit(parts
, 7);
2953 /* We always have to draw at least one sprite to make sure there is a boundingbox and a sprite with the
2954 * correct offset for the childsprites.
2955 * So, draw the (completely empty) sprite of the default foundations. */
2956 goto draw_default_foundation
;
2959 StartSpriteCombine();
2960 for (int i
= 0; i
< 8; i
++) {
2961 if (HasBit(parts
, i
)) {
2962 AddSortableSpriteToDraw(image
+ i
, PAL_NONE
, ti
->x
, ti
->y
, 16, 16, 7, ti
->z
);
2968 OffsetGroundSprite(31, 1);
2969 ti
->z
+= ApplyPixelFoundationToSlope(FOUNDATION_LEVELED
, &ti
->tileh
);
2971 draw_default_foundation
:
2972 DrawFoundation(ti
, FOUNDATION_LEVELED
);
2976 if (IsBuoy(ti
->tile
)) {
2977 DrawWaterClassGround(ti
);
2978 SpriteID sprite
= GetCanalSprite(CF_BUOY
, ti
->tile
);
2979 if (sprite
!= 0) total_offset
= sprite
- SPR_IMG_BUOY
;
2980 } else if (IsDock(ti
->tile
) || (IsOilRig(ti
->tile
) && IsTileOnWater(ti
->tile
))) {
2981 if (ti
->tileh
== SLOPE_FLAT
) {
2982 DrawWaterClassGround(ti
);
2984 assert(IsDock(ti
->tile
));
2985 TileIndex water_tile
= ti
->tile
+ TileOffsByDiagDir(GetDockDirection(ti
->tile
));
2986 WaterClass wc
= HasTileWaterClass(water_tile
) ? GetWaterClass(water_tile
) : WATER_CLASS_INVALID
;
2987 if (wc
== WATER_CLASS_SEA
) {
2988 DrawShoreTile(ti
->tileh
);
2990 DrawClearLandTile(ti
, 3);
2994 if (layout
!= nullptr) {
2995 /* Sprite layout which needs preprocessing */
2996 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
2997 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
2999 FOR_EACH_SET_BIT(var10
, var10_values
) {
3000 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, var10
);
3001 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
3003 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
3004 t
= &tmp_rail_layout
;
3006 } else if (statspec
!= nullptr) {
3007 /* Simple sprite layout */
3008 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 0);
3009 if (HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
)) {
3010 ground_relocation
= GetCustomStationRelocation(statspec
, st
, ti
->tile
, 1);
3012 ground_relocation
+= rti
->fallback_railtype
;
3015 SpriteID image
= t
->ground
.sprite
;
3016 PaletteID pal
= t
->ground
.pal
;
3017 RailTrackOffset overlay_offset
;
3018 if (rti
!= nullptr && rti
->UsesOverlay() && SplitGroundSpriteForOverlay(ti
, &image
, &overlay_offset
)) {
3019 SpriteID ground
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_GROUND
);
3020 DrawGroundSprite(image
, PAL_NONE
);
3021 DrawGroundSprite(ground
+ overlay_offset
, PAL_NONE
);
3023 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationReservation(ti
->tile
)) {
3024 SpriteID overlay
= GetCustomRailSprite(rti
, ti
->tile
, RTSG_OVERLAY
);
3025 DrawGroundSprite(overlay
+ overlay_offset
, PALETTE_CRASH
);
3028 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
3029 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
3030 DrawGroundSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
));
3032 /* PBS debugging, draw reserved tracks darker */
3033 if (_game_mode
!= GM_MENU
&& _settings_client
.gui
.show_track_reservation
&& HasStationRail(ti
->tile
) && HasStationReservation(ti
->tile
)) {
3034 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(ti
->tile
));
3035 DrawGroundSprite(GetRailStationAxis(ti
->tile
) == AXIS_X
? rti
->base_sprites
.single_x
: rti
->base_sprites
.single_y
, PALETTE_CRASH
);
3040 if (HasStationRail(ti
->tile
) && HasRailCatenaryDrawn(GetRailType(ti
->tile
))) DrawRailCatenary(ti
);
3042 if (IsRoadStop(ti
->tile
)) {
3043 RoadType road_rt
= GetRoadTypeRoad(ti
->tile
);
3044 RoadType tram_rt
= GetRoadTypeTram(ti
->tile
);
3045 const RoadTypeInfo
* road_rti
= road_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(road_rt
);
3046 const RoadTypeInfo
* tram_rti
= tram_rt
== INVALID_ROADTYPE
? nullptr : GetRoadTypeInfo(tram_rt
);
3048 if (IsDriveThroughStopTile(ti
->tile
)) {
3049 Axis axis
= GetRoadStopDir(ti
->tile
) == DIAGDIR_NE
? AXIS_X
: AXIS_Y
;
3050 uint sprite_offset
= axis
== AXIS_X
? 1 : 0;
3052 DrawRoadOverlays(ti
, PAL_NONE
, road_rti
, tram_rti
, sprite_offset
, sprite_offset
);
3054 /* Non-drivethrough road stops are only valid for roads. */
3055 assert(road_rt
!= INVALID_ROADTYPE
&& tram_rt
== INVALID_ROADTYPE
);
3057 if (road_rti
->UsesOverlay()) {
3058 DiagDirection dir
= GetRoadStopDir(ti
->tile
);
3059 SpriteID ground
= GetCustomRoadSprite(road_rti
, ti
->tile
, ROTSG_ROADSTOP
);
3060 DrawGroundSprite(ground
+ dir
, PAL_NONE
);
3064 /* Draw road, tram catenary */
3065 DrawRoadCatenary(ti
);
3068 if (IsRailWaypoint(ti
->tile
)) {
3069 /* Don't offset the waypoint graphics; they're always the same. */
3073 DrawRailTileSeq(ti
, t
, TO_BUILDINGS
, total_offset
, relocation
, palette
);
3076 void StationPickerDrawSprite(int x
, int y
, StationType st
, RailType railtype
, RoadType roadtype
, int image
)
3078 int32 total_offset
= 0;
3079 PaletteID pal
= COMPANY_SPRITE_COLOUR(_local_company
);
3080 const DrawTileSprites
*t
= GetStationTileLayout(st
, image
);
3081 const RailtypeInfo
*rti
= nullptr;
3083 if (railtype
!= INVALID_RAILTYPE
) {
3084 rti
= GetRailTypeInfo(railtype
);
3085 total_offset
= rti
->GetRailtypeSpriteOffset();
3088 SpriteID img
= t
->ground
.sprite
;
3089 RailTrackOffset overlay_offset
;
3090 if (rti
!= nullptr && rti
->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img
, &overlay_offset
)) {
3091 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
3092 DrawSprite(img
, PAL_NONE
, x
, y
);
3093 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
3095 DrawSprite(img
+ total_offset
, HasBit(img
, PALETTE_MODIFIER_COLOUR
) ? pal
: PAL_NONE
, x
, y
);
3098 if (roadtype
!= INVALID_ROADTYPE
) {
3099 const RoadTypeInfo
* rti
= GetRoadTypeInfo(roadtype
);
3101 /* Drive-through stop */
3102 uint sprite_offset
= 5 - image
;
3104 /* Road underlay takes precedence over tram */
3105 if (rti
->UsesOverlay()) {
3106 SpriteID ground
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_GROUND
);
3107 DrawSprite(ground
+ sprite_offset
, PAL_NONE
, x
, y
);
3109 SpriteID overlay
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_OVERLAY
);
3110 if (overlay
) DrawSprite(overlay
+ sprite_offset
, PAL_NONE
, x
, y
);
3111 } else if (RoadTypeIsTram(roadtype
)) {
3112 DrawSprite(SPR_TRAMWAY_TRAM
+ sprite_offset
, PAL_NONE
, x
, y
);
3116 if (RoadTypeIsRoad(roadtype
) && rti
->UsesOverlay()) {
3117 SpriteID ground
= GetCustomRoadSprite(rti
, INVALID_TILE
, ROTSG_ROADSTOP
);
3118 DrawSprite(ground
+ image
, PAL_NONE
, x
, y
);
3123 /* Default waypoint has no railtype specific sprites */
3124 DrawRailTileSeqInGUI(x
, y
, t
, st
== STATION_WAYPOINT
? 0 : total_offset
, 0, pal
);
3127 static int GetSlopePixelZ_Station(TileIndex tile
, uint x
, uint y
)
3129 return GetTileMaxPixelZ(tile
);
3132 static Foundation
GetFoundation_Station(TileIndex tile
, Slope tileh
)
3134 return FlatteningFoundation(tileh
);
3137 static void GetTileDesc_Station(TileIndex tile
, TileDesc
*td
)
3139 td
->owner
[0] = GetTileOwner(tile
);
3141 if (IsRoadStopTile(tile
)) {
3142 RoadType road_rt
= GetRoadTypeRoad(tile
);
3143 RoadType tram_rt
= GetRoadTypeTram(tile
);
3144 Owner road_owner
= INVALID_OWNER
;
3145 Owner tram_owner
= INVALID_OWNER
;
3146 if (road_rt
!= INVALID_ROADTYPE
) {
3147 const RoadTypeInfo
*rti
= GetRoadTypeInfo(road_rt
);
3148 td
->roadtype
= rti
->strings
.name
;
3149 td
->road_speed
= rti
->max_speed
/ 2;
3150 road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
3153 if (tram_rt
!= INVALID_ROADTYPE
) {
3154 const RoadTypeInfo
*rti
= GetRoadTypeInfo(tram_rt
);
3155 td
->tramtype
= rti
->strings
.name
;
3156 td
->tram_speed
= rti
->max_speed
/ 2;
3157 tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
3160 if (IsDriveThroughStopTile(tile
)) {
3161 /* Is there a mix of owners? */
3162 if ((tram_owner
!= INVALID_OWNER
&& tram_owner
!= td
->owner
[0]) ||
3163 (road_owner
!= INVALID_OWNER
&& road_owner
!= td
->owner
[0])) {
3165 if (road_owner
!= INVALID_OWNER
) {
3166 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_ROAD_OWNER
;
3167 td
->owner
[i
] = road_owner
;
3170 if (tram_owner
!= INVALID_OWNER
) {
3171 td
->owner_type
[i
] = STR_LAND_AREA_INFORMATION_TRAM_OWNER
;
3172 td
->owner
[i
] = tram_owner
;
3178 td
->build_date
= BaseStation::GetByTile(tile
)->build_date
;
3180 if (HasStationTileRail(tile
)) {
3181 const StationSpec
*spec
= GetStationSpec(tile
);
3183 if (spec
!= nullptr) {
3184 td
->station_class
= StationClass::Get(spec
->cls_id
)->name
;
3185 td
->station_name
= spec
->name
;
3187 if (spec
->grf_prop
.grffile
!= nullptr) {
3188 const GRFConfig
*gc
= GetGRFConfig(spec
->grf_prop
.grffile
->grfid
);
3189 td
->grf
= gc
->GetName();
3193 const RailtypeInfo
*rti
= GetRailTypeInfo(GetRailType(tile
));
3194 td
->rail_speed
= rti
->max_speed
;
3195 td
->railtype
= rti
->strings
.name
;
3198 if (IsAirport(tile
)) {
3199 const AirportSpec
*as
= Station::GetByTile(tile
)->airport
.GetSpec();
3200 td
->airport_class
= AirportClass::Get(as
->cls_id
)->name
;
3201 td
->airport_name
= as
->name
;
3203 const AirportTileSpec
*ats
= AirportTileSpec::GetByTile(tile
);
3204 td
->airport_tile_name
= ats
->name
;
3206 if (as
->grf_prop
.grffile
!= nullptr) {
3207 const GRFConfig
*gc
= GetGRFConfig(as
->grf_prop
.grffile
->grfid
);
3208 td
->grf
= gc
->GetName();
3209 } else if (ats
->grf_prop
.grffile
!= nullptr) {
3210 const GRFConfig
*gc
= GetGRFConfig(ats
->grf_prop
.grffile
->grfid
);
3211 td
->grf
= gc
->GetName();
3216 switch (GetStationType(tile
)) {
3217 default: NOT_REACHED();
3218 case STATION_RAIL
: str
= STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION
; break;
3219 case STATION_AIRPORT
:
3220 str
= (IsHangar(tile
) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR
: STR_LAI_STATION_DESCRIPTION_AIRPORT
);
3222 case STATION_TRUCK
: str
= STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA
; break;
3223 case STATION_BUS
: str
= STR_LAI_STATION_DESCRIPTION_BUS_STATION
; break;
3224 case STATION_OILRIG
: {
3225 const Industry
*i
= Station::GetByTile(tile
)->industry
;
3226 const IndustrySpec
*is
= GetIndustrySpec(i
->type
);
3227 td
->owner
[0] = i
->owner
;
3229 if (is
->grf_prop
.grffile
!= nullptr) td
->grf
= GetGRFConfig(is
->grf_prop
.grffile
->grfid
)->GetName();
3232 case STATION_DOCK
: str
= STR_LAI_STATION_DESCRIPTION_SHIP_DOCK
; break;
3233 case STATION_BUOY
: str
= STR_LAI_STATION_DESCRIPTION_BUOY
; break;
3234 case STATION_WAYPOINT
: str
= STR_LAI_STATION_DESCRIPTION_WAYPOINT
; break;
3240 static TrackStatus
GetTileTrackStatus_Station(TileIndex tile
, TransportType mode
, uint sub_mode
, DiagDirection side
)
3242 TrackBits trackbits
= TRACK_BIT_NONE
;
3245 case TRANSPORT_RAIL
:
3246 if (HasStationRail(tile
) && !IsStationTileBlocked(tile
)) {
3247 trackbits
= TrackToTrackBits(GetRailStationTrack(tile
));
3251 case TRANSPORT_WATER
:
3252 /* buoy is coded as a station, it is always on open water */
3254 trackbits
= TRACK_BIT_ALL
;
3255 /* remove tracks that connect NE map edge */
3256 if (TileX(tile
) == 0) trackbits
&= ~(TRACK_BIT_X
| TRACK_BIT_UPPER
| TRACK_BIT_RIGHT
);
3257 /* remove tracks that connect NW map edge */
3258 if (TileY(tile
) == 0) trackbits
&= ~(TRACK_BIT_Y
| TRACK_BIT_LEFT
| TRACK_BIT_UPPER
);
3262 case TRANSPORT_ROAD
:
3263 if (IsRoadStop(tile
)) {
3264 RoadTramType rtt
= (RoadTramType
)sub_mode
;
3265 if (!HasTileRoadType(tile
, rtt
)) break;
3267 DiagDirection dir
= GetRoadStopDir(tile
);
3268 Axis axis
= DiagDirToAxis(dir
);
3270 if (side
!= INVALID_DIAGDIR
) {
3271 if (axis
!= DiagDirToAxis(side
) || (IsStandardRoadStopTile(tile
) && dir
!= side
)) break;
3274 trackbits
= AxisToTrackBits(axis
);
3282 return CombineTrackStatus(TrackBitsToTrackdirBits(trackbits
), TRACKDIR_BIT_NONE
);
3286 static void TileLoop_Station(TileIndex tile
)
3288 /* FIXME -- GetTileTrackStatus_Station -> animated stationtiles
3289 * hardcoded.....not good */
3290 switch (GetStationType(tile
)) {
3291 case STATION_AIRPORT
:
3292 AirportTileAnimationTrigger(Station::GetByTile(tile
), tile
, AAT_TILELOOP
);
3296 if (!IsTileFlat(tile
)) break; // only handle water part
3299 case STATION_OILRIG
: //(station part)
3301 TileLoop_Water(tile
);
3309 static void AnimateTile_Station(TileIndex tile
)
3311 if (HasStationRail(tile
)) {
3312 AnimateStationTile(tile
);
3316 if (IsAirport(tile
)) {
3317 AnimateAirportTile(tile
);
3322 static bool ClickTile_Station(TileIndex tile
)
3324 const BaseStation
*bst
= BaseStation::GetByTile(tile
);
3326 if (bst
->facilities
& FACIL_WAYPOINT
) {
3327 ShowWaypointWindow(Waypoint::From(bst
));
3328 } else if (IsHangar(tile
)) {
3329 const Station
*st
= Station::From(bst
);
3330 ShowDepotWindow(st
->airport
.GetHangarTile(st
->airport
.GetHangarNum(tile
)), VEH_AIRCRAFT
);
3332 ShowStationViewWindow(bst
->index
);
3337 static VehicleEnterTileStatus
VehicleEnter_Station(Vehicle
*v
, TileIndex tile
, int x
, int y
)
3339 if (v
->type
== VEH_TRAIN
) {
3340 StationID station_id
= GetStationIndex(tile
);
3341 if (!v
->current_order
.ShouldStopAtStation(v
, station_id
)) return VETSB_CONTINUE
;
3342 if (!IsRailStation(tile
) || !v
->IsFrontEngine()) return VETSB_CONTINUE
;
3346 int stop
= GetTrainStopLocation(station_id
, tile
, Train::From(v
), &station_ahead
, &station_length
);
3348 /* Stop whenever that amount of station ahead + the distance from the
3349 * begin of the platform to the stop location is longer than the length
3350 * of the platform. Station ahead 'includes' the current tile where the
3351 * vehicle is on, so we need to subtract that. */
3352 if (stop
+ station_ahead
- (int)TILE_SIZE
>= station_length
) return VETSB_CONTINUE
;
3354 DiagDirection dir
= DirToDiagDir(v
->direction
);
3359 if (DiagDirToAxis(dir
) != AXIS_X
) Swap(x
, y
);
3360 if (y
== TILE_SIZE
/ 2) {
3361 if (dir
!= DIAGDIR_SE
&& dir
!= DIAGDIR_SW
) x
= TILE_SIZE
- 1 - x
;
3362 stop
&= TILE_SIZE
- 1;
3365 return VETSB_ENTERED_STATION
| (VehicleEnterTileStatus
)(station_id
<< VETS_STATION_ID_OFFSET
); // enter station
3366 } else if (x
< stop
) {
3367 v
->vehstatus
|= VS_TRAIN_SLOWING
;
3368 uint16 spd
= max(0, (stop
- x
) * 20 - 15);
3369 if (spd
< v
->cur_speed
) v
->cur_speed
= spd
;
3372 } else if (v
->type
== VEH_ROAD
) {
3373 RoadVehicle
*rv
= RoadVehicle::From(v
);
3374 if (rv
->state
< RVSB_IN_ROAD_STOP
&& !IsReversingRoadTrackdir((Trackdir
)rv
->state
) && rv
->frame
== 0) {
3375 if (IsRoadStop(tile
) && rv
->IsFrontEngine()) {
3376 /* Attempt to allocate a parking bay in a road stop */
3377 return RoadStop::GetByTile(tile
, GetRoadStopType(tile
))->Enter(rv
) ? VETSB_CONTINUE
: VETSB_CANNOT_ENTER
;
3382 return VETSB_CONTINUE
;
3386 * Run the watched cargo callback for all houses in the catchment area.
3387 * @param st Station.
3389 void TriggerWatchedCargoCallbacks(Station
*st
)
3391 /* Collect cargoes accepted since the last big tick. */
3392 CargoTypes cargoes
= 0;
3393 for (CargoID cid
= 0; cid
< NUM_CARGO
; cid
++) {
3394 if (HasBit(st
->goods
[cid
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
)) SetBit(cargoes
, cid
);
3397 /* Anything to do? */
3398 if (cargoes
== 0) return;
3400 /* Loop over all houses in the catchment. */
3401 BitmapTileIterator
it(st
->catchment_tiles
);
3402 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
3403 if (IsTileType(tile
, MP_HOUSE
)) {
3404 WatchedCargoCallback(tile
, cargoes
);
3410 * This function is called for each station once every 250 ticks.
3411 * Not all stations will get the tick at the same time.
3412 * @param st the station receiving the tick.
3413 * @return true if the station is still valid (wasn't deleted)
3415 static bool StationHandleBigTick(BaseStation
*st
)
3417 if (!st
->IsInUse()) {
3418 if (++st
->delete_ctr
>= 8) delete st
;
3422 if (Station::IsExpected(st
)) {
3423 TriggerWatchedCargoCallbacks(Station::From(st
));
3425 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3426 ClrBit(Station::From(st
)->goods
[i
].status
, GoodsEntry::GES_ACCEPTED_BIGTICK
);
3431 if ((st
->facilities
& FACIL_WAYPOINT
) == 0) UpdateStationAcceptance(Station::From(st
), true);
3436 static inline void byte_inc_sat(byte
*p
)
3443 * Truncate the cargo by a specific amount.
3444 * @param cs The type of cargo to perform the truncation for.
3445 * @param ge The goods entry, of the station, to truncate.
3446 * @param amount The amount to truncate the cargo by.
3448 static void TruncateCargo(const CargoSpec
*cs
, GoodsEntry
*ge
, uint amount
= UINT_MAX
)
3450 /* If truncating also punish the source stations' ratings to
3451 * decrease the flow of incoming cargo. */
3453 StationCargoAmountMap waiting_per_source
;
3454 ge
->cargo
.Truncate(amount
, &waiting_per_source
);
3455 for (StationCargoAmountMap::iterator
i(waiting_per_source
.begin()); i
!= waiting_per_source
.end(); ++i
) {
3456 Station
*source_station
= Station::GetIfValid(i
->first
);
3457 if (source_station
== nullptr) continue;
3459 GoodsEntry
&source_ge
= source_station
->goods
[cs
->Index()];
3460 source_ge
.max_waiting_cargo
= max(source_ge
.max_waiting_cargo
, i
->second
);
3464 static void UpdateStationRating(Station
*st
)
3466 bool waiting_changed
= false;
3468 byte_inc_sat(&st
->time_since_load
);
3469 byte_inc_sat(&st
->time_since_unload
);
3471 const CargoSpec
*cs
;
3472 FOR_ALL_CARGOSPECS(cs
) {
3473 GoodsEntry
*ge
= &st
->goods
[cs
->Index()];
3474 /* Slowly increase the rating back to his original level in the case we
3475 * didn't deliver cargo yet to this station. This happens when a bribe
3476 * failed while you didn't moved that cargo yet to a station. */
3477 if (!ge
->HasRating() && ge
->rating
< INITIAL_STATION_RATING
) {
3481 /* Only change the rating if we are moving this cargo */
3482 if (ge
->HasRating()) {
3483 byte_inc_sat(&ge
->time_since_pickup
);
3484 if (ge
->time_since_pickup
== 255 && _settings_game
.order
.selectgoods
) {
3485 ClrBit(ge
->status
, GoodsEntry::GES_RATING
);
3487 TruncateCargo(cs
, ge
);
3488 waiting_changed
= true;
3494 uint waiting
= ge
->cargo
.AvailableCount();
3496 /* num_dests is at least 1 if there is any cargo as
3497 * INVALID_STATION is also a destination.
3499 uint num_dests
= (uint
)ge
->cargo
.Packets()->MapSize();
3501 /* Average amount of cargo per next hop, but prefer solitary stations
3502 * with only one or two next hops. They are allowed to have more
3503 * cargo waiting per next hop.
3504 * With manual cargo distribution waiting_avg = waiting / 2 as then
3505 * INVALID_STATION is the only destination.
3507 uint waiting_avg
= waiting
/ (num_dests
+ 1);
3509 if (HasBit(cs
->callback_mask
, CBM_CARGO_STATION_RATING_CALC
)) {
3510 /* Perform custom station rating. If it succeeds the speed, days in transit and
3511 * waiting cargo ratings must not be executed. */
3513 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
3514 uint last_speed
= ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
: 0xFF;
3516 uint32 var18
= min(ge
->time_since_pickup
, 0xFF) | (min(ge
->max_waiting_cargo
, 0xFFFF) << 8) | (min(last_speed
, 0xFF) << 24);
3517 /* Convert to the 'old' vehicle types */
3518 uint32 var10
= (st
->last_vehicle_type
== VEH_INVALID
) ? 0x0 : (st
->last_vehicle_type
+ 0x10);
3519 uint16 callback
= GetCargoCallback(CBID_CARGO_STATION_RATING_CALC
, var10
, var18
, cs
);
3520 if (callback
!= CALLBACK_FAILED
) {
3522 rating
= GB(callback
, 0, 14);
3524 /* Simulate a 15 bit signed value */
3525 if (HasBit(callback
, 14)) rating
-= 0x4000;
3530 int b
= ge
->last_speed
- 85;
3531 if (b
>= 0) rating
+= b
>> 2;
3533 byte waittime
= ge
->time_since_pickup
;
3534 if (st
->last_vehicle_type
== VEH_SHIP
) waittime
>>= 2;
3535 if (waittime
<= 21) rating
+= 25;
3536 if (waittime
<= 12) rating
+= 25;
3537 if (waittime
<= 6) rating
+= 45;
3538 if (waittime
<= 3) rating
+= 35;
3541 if (ge
->max_waiting_cargo
<= 1500) rating
+= 55;
3542 if (ge
->max_waiting_cargo
<= 1000) rating
+= 35;
3543 if (ge
->max_waiting_cargo
<= 600) rating
+= 10;
3544 if (ge
->max_waiting_cargo
<= 300) rating
+= 20;
3545 if (ge
->max_waiting_cargo
<= 100) rating
+= 10;
3548 if (Company::IsValidID(st
->owner
) && HasBit(st
->town
->statues
, st
->owner
)) rating
+= 26;
3550 byte age
= ge
->last_age
;
3551 if (age
< 3) rating
+= 10;
3552 if (age
< 2) rating
+= 10;
3553 if (age
< 1) rating
+= 13;
3556 int or_
= ge
->rating
; // old rating
3558 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
3559 ge
->rating
= rating
= or_
+ Clamp(Clamp(rating
, 0, 255) - or_
, -2, 2);
3561 /* if rating is <= 64 and more than 100 items waiting on average per destination,
3562 * remove some random amount of goods from the station */
3563 if (rating
<= 64 && waiting_avg
>= 100) {
3564 int dec
= Random() & 0x1F;
3565 if (waiting_avg
< 200) dec
&= 7;
3566 waiting
-= (dec
+ 1) * num_dests
;
3567 waiting_changed
= true;
3570 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
3571 if (rating
<= 127 && waiting
!= 0) {
3572 uint32 r
= Random();
3573 if (rating
<= (int)GB(r
, 0, 7)) {
3574 /* Need to have int, otherwise it will just overflow etc. */
3575 waiting
= max((int)waiting
- (int)((GB(r
, 8, 2) - 1) * num_dests
), 0);
3576 waiting_changed
= true;
3580 /* At some point we really must cap the cargo. Previously this
3581 * was a strict 4095, but now we'll have a less strict, but
3582 * increasingly aggressive truncation of the amount of cargo. */
3583 static const uint WAITING_CARGO_THRESHOLD
= 1 << 12;
3584 static const uint WAITING_CARGO_CUT_FACTOR
= 1 << 6;
3585 static const uint MAX_WAITING_CARGO
= 1 << 15;
3587 if (waiting
> WAITING_CARGO_THRESHOLD
) {
3588 uint difference
= waiting
- WAITING_CARGO_THRESHOLD
;
3589 waiting
-= (difference
/ WAITING_CARGO_CUT_FACTOR
);
3591 waiting
= min(waiting
, MAX_WAITING_CARGO
);
3592 waiting_changed
= true;
3595 /* We can't truncate cargo that's already reserved for loading.
3596 * Thus StoredCount() here. */
3597 if (waiting_changed
&& waiting
< ge
->cargo
.AvailableCount()) {
3598 /* Feed back the exact own waiting cargo at this station for the
3599 * next rating calculation. */
3600 ge
->max_waiting_cargo
= 0;
3602 TruncateCargo(cs
, ge
, ge
->cargo
.AvailableCount() - waiting
);
3604 /* If the average number per next hop is low, be more forgiving. */
3605 ge
->max_waiting_cargo
= waiting_avg
;
3611 StationID index
= st
->index
;
3612 if (waiting_changed
) {
3613 SetWindowDirty(WC_STATION_VIEW
, index
); // update whole window
3615 SetWindowWidgetDirty(WC_STATION_VIEW
, index
, WID_SV_ACCEPT_RATING_LIST
); // update only ratings list
3620 * Reroute cargo of type c at station st or in any vehicles unloading there.
3621 * Make sure the cargo's new next hop is neither "avoid" nor "avoid2".
3622 * @param st Station to be rerouted at.
3623 * @param c Type of cargo.
3624 * @param avoid Original next hop of cargo, avoid this.
3625 * @param avoid2 Another station to be avoided when rerouting.
3627 void RerouteCargo(Station
*st
, CargoID c
, StationID avoid
, StationID avoid2
)
3629 GoodsEntry
&ge
= st
->goods
[c
];
3631 /* Reroute cargo in station. */
3632 ge
.cargo
.Reroute(UINT_MAX
, &ge
.cargo
, avoid
, avoid2
, &ge
);
3634 /* Reroute cargo staged to be transferred. */
3635 for (std::list
<Vehicle
*>::iterator
it(st
->loading_vehicles
.begin()); it
!= st
->loading_vehicles
.end(); ++it
) {
3636 for (Vehicle
*v
= *it
; v
!= nullptr; v
= v
->Next()) {
3637 if (v
->cargo_type
!= c
) continue;
3638 v
->cargo
.Reroute(UINT_MAX
, &v
->cargo
, avoid
, avoid2
, &ge
);
3644 * Check all next hops of cargo packets in this station for existence of a
3645 * a valid link they may use to travel on. Reroute any cargo not having a valid
3646 * link and remove timed out links found like this from the linkgraph. We're
3647 * not all links here as that is expensive and useless. A link no one is using
3648 * doesn't hurt either.
3649 * @param from Station to check.
3651 void DeleteStaleLinks(Station
*from
)
3653 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
3654 const bool auto_distributed
= (_settings_game
.linkgraph
.GetDistributionType(c
) != DT_MANUAL
);
3655 GoodsEntry
&ge
= from
->goods
[c
];
3656 LinkGraph
*lg
= LinkGraph::GetIfValid(ge
.link_graph
);
3657 if (lg
== nullptr) continue;
3658 Node node
= (*lg
)[ge
.node
];
3659 for (EdgeIterator
it(node
.Begin()); it
!= node
.End();) {
3660 Edge edge
= it
->second
;
3661 Station
*to
= Station::Get((*lg
)[it
->first
].Station());
3662 assert(to
->goods
[c
].node
== it
->first
);
3663 ++it
; // Do that before removing the edge. Anything else may crash.
3664 assert(_date
>= edge
.LastUpdate());
3665 uint timeout
= LinkGraph::MIN_TIMEOUT_DISTANCE
+ (DistanceManhattan(from
->xy
, to
->xy
) >> 3);
3666 if ((uint
)(_date
- edge
.LastUpdate()) > timeout
) {
3667 bool updated
= false;
3669 if (auto_distributed
) {
3670 /* Have all vehicles refresh their next hops before deciding to
3671 * remove the node. */
3673 std::vector
<Vehicle
*> vehicles
;
3674 FOR_ALL_ORDER_LISTS(l
) {
3675 bool found_from
= false;
3676 bool found_to
= false;
3677 for (Order
*order
= l
->GetFirstOrder(); order
!= nullptr; order
= order
->next
) {
3678 if (!order
->IsType(OT_GOTO_STATION
) && !order
->IsType(OT_IMPLICIT
)) continue;
3679 if (order
->GetDestination() == from
->index
) {
3681 if (found_to
) break;
3682 } else if (order
->GetDestination() == to
->index
) {
3684 if (found_from
) break;
3687 if (!found_to
|| !found_from
) continue;
3688 vehicles
.push_back(l
->GetFirstSharedVehicle());
3691 auto iter
= vehicles
.begin();
3692 while (iter
!= vehicles
.end()) {
3695 LinkRefresher::Run(v
, false); // Don't allow merging. Otherwise lg might get deleted.
3696 if (edge
.LastUpdate() == _date
) {
3701 Vehicle
*next_shared
= v
->NextShared();
3703 *iter
= next_shared
;
3706 iter
= vehicles
.erase(iter
);
3709 if (iter
== vehicles
.end()) iter
= vehicles
.begin();
3714 /* If it's still considered dead remove it. */
3715 node
.RemoveEdge(to
->goods
[c
].node
);
3716 ge
.flows
.DeleteFlows(to
->index
);
3717 RerouteCargo(from
, c
, to
->index
, from
->index
);
3719 } else if (edge
.LastUnrestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastUnrestrictedUpdate()) > timeout
) {
3721 ge
.flows
.RestrictFlows(to
->index
);
3722 RerouteCargo(from
, c
, to
->index
, from
->index
);
3723 } else if (edge
.LastRestrictedUpdate() != INVALID_DATE
&& (uint
)(_date
- edge
.LastRestrictedUpdate()) > timeout
) {
3727 assert(_date
>= lg
->LastCompression());
3728 if ((uint
)(_date
- lg
->LastCompression()) > LinkGraph::COMPRESSION_INTERVAL
) {
3735 * Increase capacity for a link stat given by station cargo and next hop.
3736 * @param st Station to get the link stats from.
3737 * @param cargo Cargo to increase stat for.
3738 * @param next_station_id Station the consist will be travelling to next.
3739 * @param capacity Capacity to add to link stat.
3740 * @param usage Usage to add to link stat.
3741 * @param mode Update mode to be applied.
3743 void IncreaseStats(Station
*st
, CargoID cargo
, StationID next_station_id
, uint capacity
, uint usage
, EdgeUpdateMode mode
)
3745 GoodsEntry
&ge1
= st
->goods
[cargo
];
3746 Station
*st2
= Station::Get(next_station_id
);
3747 GoodsEntry
&ge2
= st2
->goods
[cargo
];
3748 LinkGraph
*lg
= nullptr;
3749 if (ge1
.link_graph
== INVALID_LINK_GRAPH
) {
3750 if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3751 if (LinkGraph::CanAllocateItem()) {
3752 lg
= new LinkGraph(cargo
);
3753 LinkGraphSchedule::instance
.Queue(lg
);
3754 ge2
.link_graph
= lg
->index
;
3755 ge2
.node
= lg
->AddNode(st2
);
3757 DEBUG(misc
, 0, "Can't allocate link graph");
3760 lg
= LinkGraph::Get(ge2
.link_graph
);
3763 ge1
.link_graph
= lg
->index
;
3764 ge1
.node
= lg
->AddNode(st
);
3766 } else if (ge2
.link_graph
== INVALID_LINK_GRAPH
) {
3767 lg
= LinkGraph::Get(ge1
.link_graph
);
3768 ge2
.link_graph
= lg
->index
;
3769 ge2
.node
= lg
->AddNode(st2
);
3771 lg
= LinkGraph::Get(ge1
.link_graph
);
3772 if (ge1
.link_graph
!= ge2
.link_graph
) {
3773 LinkGraph
*lg2
= LinkGraph::Get(ge2
.link_graph
);
3774 if (lg
->Size() < lg2
->Size()) {
3775 LinkGraphSchedule::instance
.Unqueue(lg
);
3776 lg2
->Merge(lg
); // Updates GoodsEntries of lg
3779 LinkGraphSchedule::instance
.Unqueue(lg2
);
3780 lg
->Merge(lg2
); // Updates GoodsEntries of lg2
3784 if (lg
!= nullptr) {
3785 (*lg
)[ge1
.node
].UpdateEdge(ge2
.node
, capacity
, usage
, mode
);
3790 * Increase capacity for all link stats associated with vehicles in the given consist.
3791 * @param st Station to get the link stats from.
3792 * @param front First vehicle in the consist.
3793 * @param next_station_id Station the consist will be travelling to next.
3795 void IncreaseStats(Station
*st
, const Vehicle
*front
, StationID next_station_id
)
3797 for (const Vehicle
*v
= front
; v
!= nullptr; v
= v
->Next()) {
3798 if (v
->refit_cap
> 0) {
3799 /* The cargo count can indeed be higher than the refit_cap if
3800 * wagons have been auto-replaced and subsequently auto-
3801 * refitted to a higher capacity. The cargo gets redistributed
3802 * among the wagons in that case.
3803 * As usage is not such an important figure anyway we just
3804 * ignore the additional cargo then.*/
3805 IncreaseStats(st
, v
->cargo_type
, next_station_id
, v
->refit_cap
,
3806 min(v
->refit_cap
, v
->cargo
.StoredCount()), EUM_INCREASE
);
3811 /* called for every station each tick */
3812 static void StationHandleSmallTick(BaseStation
*st
)
3814 if ((st
->facilities
& FACIL_WAYPOINT
) != 0 || !st
->IsInUse()) return;
3816 byte b
= st
->delete_ctr
+ 1;
3817 if (b
>= STATION_RATING_TICKS
) b
= 0;
3820 if (b
== 0) UpdateStationRating(Station::From(st
));
3823 void OnTick_Station()
3825 if (_game_mode
== GM_EDITOR
) return;
3828 FOR_ALL_BASE_STATIONS(st
) {
3829 StationHandleSmallTick(st
);
3831 /* Clean up the link graph about once a week. */
3832 if (Station::IsExpected(st
) && (_tick_counter
+ st
->index
) % STATION_LINKGRAPH_TICKS
== 0) {
3833 DeleteStaleLinks(Station::From(st
));
3836 /* Run STATION_ACCEPTANCE_TICKS = 250 tick interval trigger for station animation.
3837 * Station index is included so that triggers are not all done
3838 * at the same time. */
3839 if ((_tick_counter
+ st
->index
) % STATION_ACCEPTANCE_TICKS
== 0) {
3840 /* Stop processing this station if it was deleted */
3841 if (!StationHandleBigTick(st
)) continue;
3842 TriggerStationAnimation(st
, st
->xy
, SAT_250_TICKS
);
3843 if (Station::IsExpected(st
)) AirportAnimationTrigger(Station::From(st
), AAT_STATION_250_TICKS
);
3848 /** Monthly loop for stations. */
3849 void StationMonthlyLoop()
3853 FOR_ALL_STATIONS(st
) {
3854 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3855 GoodsEntry
*ge
= &st
->goods
[i
];
3856 SB(ge
->status
, GoodsEntry::GES_LAST_MONTH
, 1, GB(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
, 1));
3857 ClrBit(ge
->status
, GoodsEntry::GES_CURRENT_MONTH
);
3863 void ModifyStationRatingAround(TileIndex tile
, Owner owner
, int amount
, uint radius
)
3865 ForAllStationsRadius(tile
, radius
, [&](Station
*st
) {
3866 if (st
->owner
== owner
) {
3867 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
3868 GoodsEntry
*ge
= &st
->goods
[i
];
3870 if (ge
->status
!= 0) {
3871 ge
->rating
= Clamp(ge
->rating
+ amount
, 0, 255);
3878 static uint
UpdateStationWaiting(Station
*st
, CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
)
3880 /* We can't allocate a CargoPacket? Then don't do anything
3881 * at all; i.e. just discard the incoming cargo. */
3882 if (!CargoPacket::CanAllocateItem()) return 0;
3884 GoodsEntry
&ge
= st
->goods
[type
];
3885 amount
+= ge
.amount_fract
;
3886 ge
.amount_fract
= GB(amount
, 0, 8);
3889 /* No new "real" cargo item yet. */
3890 if (amount
== 0) return 0;
3892 StationID next
= ge
.GetVia(st
->index
);
3893 ge
.cargo
.Append(new CargoPacket(st
->index
, st
->xy
, amount
, source_type
, source_id
), next
);
3894 LinkGraph
*lg
= nullptr;
3895 if (ge
.link_graph
== INVALID_LINK_GRAPH
) {
3896 if (LinkGraph::CanAllocateItem()) {
3897 lg
= new LinkGraph(type
);
3898 LinkGraphSchedule::instance
.Queue(lg
);
3899 ge
.link_graph
= lg
->index
;
3900 ge
.node
= lg
->AddNode(st
);
3902 DEBUG(misc
, 0, "Can't allocate link graph");
3905 lg
= LinkGraph::Get(ge
.link_graph
);
3907 if (lg
!= nullptr) (*lg
)[ge
.node
].UpdateSupply(amount
);
3909 if (!ge
.HasRating()) {
3910 InvalidateWindowData(WC_STATION_LIST
, st
->index
);
3911 SetBit(ge
.status
, GoodsEntry::GES_RATING
);
3914 TriggerStationRandomisation(st
, st
->xy
, SRT_NEW_CARGO
, type
);
3915 TriggerStationAnimation(st
, st
->xy
, SAT_NEW_CARGO
, type
);
3916 AirportAnimationTrigger(st
, AAT_STATION_NEW_CARGO
, type
);
3918 SetWindowDirty(WC_STATION_VIEW
, st
->index
);
3919 st
->MarkTilesDirty(true);
3923 static bool IsUniqueStationName(const char *name
)
3927 FOR_ALL_STATIONS(st
) {
3928 if (st
->name
!= nullptr && strcmp(st
->name
, name
) == 0) return false;
3936 * @param tile unused
3937 * @param flags operation to perform
3938 * @param p1 station ID that is to be renamed
3940 * @param text the new name or an empty string when resetting to the default
3941 * @return the cost of this operation or an error
3943 CommandCost
CmdRenameStation(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
3945 Station
*st
= Station::GetIfValid(p1
);
3946 if (st
== nullptr) return CMD_ERROR
;
3948 CommandCost ret
= CheckOwnership(st
->owner
);
3949 if (ret
.Failed()) return ret
;
3951 bool reset
= StrEmpty(text
);
3954 if (Utf8StringLength(text
) >= MAX_LENGTH_STATION_NAME_CHARS
) return CMD_ERROR
;
3955 if (!IsUniqueStationName(text
)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE
);
3958 if (flags
& DC_EXEC
) {
3960 st
->name
= reset
? nullptr : stredup(text
);
3962 st
->UpdateVirtCoord();
3963 InvalidateWindowData(WC_STATION_LIST
, st
->owner
, 1);
3966 return CommandCost();
3969 static void AddNearbyStationsByCatchment(TileIndex tile
, StationList
*stations
, StationList
&nearby
)
3971 for (Station
*st
: nearby
) {
3972 if (st
->TileIsInCatchment(tile
)) stations
->insert(st
);
3977 * Find all stations around a rectangular producer (industry, house, headquarter, ...)
3979 * @param location The location/area of the producer
3980 * @param[out] stations The list to store the stations in
3981 * @param use_nearby Use nearby station list of industry/town associated with location.tile
3983 void FindStationsAroundTiles(const TileArea
&location
, StationList
* const stations
, bool use_nearby
)
3986 /* Industries and towns maintain a list of nearby stations */
3987 if (IsTileType(location
.tile
, MP_INDUSTRY
)) {
3988 /* Industry nearby stations are already filtered by catchment. */
3989 *stations
= Industry::GetByTile(location
.tile
)->stations_near
;
3991 } else if (IsTileType(location
.tile
, MP_HOUSE
)) {
3992 /* Town nearby stations need to be filtered per tile. */
3993 assert(location
.w
== 1 && location
.h
== 1);
3994 AddNearbyStationsByCatchment(location
.tile
, stations
, Town::GetByTile(location
.tile
)->stations_near
);
3999 /* Not using, or don't have a nearby stations list, so we need to scan. */
4000 std::set
<StationID
> seen_stations
;
4002 /* Scan an area around the building covering the maximum possible station
4003 * to find the possible nearby stations. */
4004 uint max_c
= _settings_game
.station
.modified_catchment
? MAX_CATCHMENT
: CA_UNMODIFIED
;
4005 TileArea ta
= TileArea(location
).Expand(max_c
);
4006 TILE_AREA_LOOP(tile
, ta
) {
4007 if (IsTileType(tile
, MP_STATION
)) seen_stations
.insert(GetStationIndex(tile
));
4010 for (StationID stationid
: seen_stations
) {
4011 Station
*st
= Station::GetIfValid(stationid
);
4012 if (st
== nullptr) continue; /* Waypoint */
4014 /* Check if station is attached to an industry */
4015 if (!_settings_game
.station
.serve_neutral_industries
&& st
->industry
!= nullptr) continue;
4017 /* Test if the tile is within the station's catchment */
4018 TILE_AREA_LOOP(tile
, location
) {
4019 if (st
->TileIsInCatchment(tile
)) {
4020 stations
->insert(st
);
4028 * Run a tile loop to find stations around a tile, on demand. Cache the result for further requests
4029 * @return pointer to a StationList containing all stations found
4031 const StationList
*StationFinder::GetStations()
4033 if (this->tile
!= INVALID_TILE
) {
4034 FindStationsAroundTiles(*this, &this->stations
);
4035 this->tile
= INVALID_TILE
;
4037 return &this->stations
;
4040 uint
MoveGoodsToStation(CargoID type
, uint amount
, SourceType source_type
, SourceID source_id
, const StationList
*all_stations
)
4042 /* Return if nothing to do. Also the rounding below fails for 0. */
4043 if (amount
== 0) return 0;
4045 Station
*st1
= nullptr; // Station with best rating
4046 Station
*st2
= nullptr; // Second best station
4047 uint best_rating1
= 0; // rating of st1
4048 uint best_rating2
= 0; // rating of st2
4050 for (Station
*st
: *all_stations
) {
4051 /* Is the station reserved exclusively for somebody else? */
4052 if (st
->owner
!= OWNER_NONE
&& st
->town
->exclusive_counter
> 0 && st
->town
->exclusivity
!= st
->owner
) continue;
4054 if (st
->goods
[type
].rating
== 0) continue; // Lowest possible rating, better not to give cargo anymore
4056 if (_settings_game
.order
.selectgoods
&& !st
->goods
[type
].HasVehicleEverTriedLoading()) continue; // Selectively servicing stations, and not this one
4058 if (IsCargoInClass(type
, CC_PASSENGERS
)) {
4059 if (st
->facilities
== FACIL_TRUCK_STOP
) continue; // passengers are never served by just a truck stop
4061 if (st
->facilities
== FACIL_BUS_STOP
) continue; // non-passengers are never served by just a bus stop
4064 /* This station can be used, add it to st1/st2 */
4065 if (st1
== nullptr || st
->goods
[type
].rating
>= best_rating1
) {
4066 st2
= st1
; best_rating2
= best_rating1
; st1
= st
; best_rating1
= st
->goods
[type
].rating
;
4067 } else if (st2
== nullptr || st
->goods
[type
].rating
>= best_rating2
) {
4068 st2
= st
; best_rating2
= st
->goods
[type
].rating
;
4072 /* no stations around at all? */
4073 if (st1
== nullptr) return 0;
4075 /* From now we'll calculate with fractal cargo amounts.
4076 * First determine how much cargo we really have. */
4077 amount
*= best_rating1
+ 1;
4079 if (st2
== nullptr) {
4080 /* only one station around */
4081 return UpdateStationWaiting(st1
, type
, amount
, source_type
, source_id
);
4084 /* several stations around, the best two (highest rating) are in st1 and st2 */
4085 assert(st1
!= nullptr);
4086 assert(st2
!= nullptr);
4087 assert(best_rating1
!= 0 || best_rating2
!= 0);
4089 /* Then determine the amount the worst station gets. We do it this way as the
4090 * best should get a bonus, which in this case is the rounding difference from
4091 * this calculation. In reality that will mean the bonus will be pretty low.
4092 * Nevertheless, the best station should always get the most cargo regardless
4093 * of rounding issues. */
4094 uint worst_cargo
= amount
* best_rating2
/ (best_rating1
+ best_rating2
);
4095 assert(worst_cargo
<= (amount
- worst_cargo
));
4097 /* And then send the cargo to the stations! */
4098 uint moved
= UpdateStationWaiting(st1
, type
, amount
- worst_cargo
, source_type
, source_id
);
4099 /* These two UpdateStationWaiting's can't be in the statement as then the order
4100 * of execution would be undefined and that could cause desyncs with callbacks. */
4101 return moved
+ UpdateStationWaiting(st2
, type
, worst_cargo
, source_type
, source_id
);
4104 void UpdateStationDockingTiles(Station
*st
)
4106 st
->docking_station
.Clear();
4108 /* For neutral stations, start with the industry area instead of dock area */
4109 const TileArea
*area
= st
->industry
!= nullptr ? &st
->industry
->location
: &st
->ship_station
;
4111 if (area
->tile
== INVALID_TILE
) return;
4113 int x
= TileX(area
->tile
);
4114 int y
= TileY(area
->tile
);
4116 /* Expand the area by a tile on each side while
4117 * making sure that we remain inside the map. */
4118 int x2
= min(x
+ area
->w
+ 1, MapSizeX());
4119 int x1
= max(x
- 1, 0);
4121 int y2
= min(y
+ area
->h
+ 1, MapSizeY());
4122 int y1
= max(y
- 1, 0);
4124 TileArea
ta(TileXY(x1
, y1
), TileXY(x2
- 1, y2
- 1));
4125 TILE_AREA_LOOP(tile
, ta
) {
4126 if (IsValidTile(tile
) && IsPossibleDockingTile(tile
)) CheckForDockingTile(tile
);
4130 void BuildOilRig(TileIndex tile
)
4132 if (!Station::CanAllocateItem()) {
4133 DEBUG(misc
, 0, "Can't allocate station for oilrig at 0x%X, reverting to oilrig only", tile
);
4137 Station
*st
= new Station(tile
);
4138 _station_kdtree
.Insert(st
->index
);
4139 st
->town
= ClosestTownFromTile(tile
, UINT_MAX
);
4141 st
->string_id
= GenerateStationName(st
, tile
, STATIONNAMING_OILRIG
);
4143 assert(IsTileType(tile
, MP_INDUSTRY
));
4144 /* Mark industry as associated both ways */
4145 st
->industry
= Industry::GetByTile(tile
);
4146 st
->industry
->neutral_station
= st
;
4147 DeleteAnimatedTile(tile
);
4148 MakeOilrig(tile
, st
->index
, GetWaterClass(tile
));
4150 st
->owner
= OWNER_NONE
;
4151 st
->airport
.type
= AT_OILRIG
;
4152 st
->airport
.Add(tile
);
4153 st
->ship_station
.Add(tile
);
4154 st
->facilities
= FACIL_AIRPORT
| FACIL_DOCK
;
4155 st
->build_date
= _date
;
4156 UpdateStationDockingTiles(st
);
4158 st
->rect
.BeforeAddTile(tile
, StationRect::ADD_FORCE
);
4160 st
->UpdateVirtCoord();
4161 st
->RecomputeCatchment();
4162 UpdateStationAcceptance(st
, false);
4165 void DeleteOilRig(TileIndex tile
)
4167 Station
*st
= Station::GetByTile(tile
);
4169 MakeWaterKeepingClass(tile
, OWNER_NONE
);
4171 /* The oil rig station is not supposed to be shared with anything else */
4172 assert(st
->facilities
== (FACIL_AIRPORT
| FACIL_DOCK
) && st
->airport
.type
== AT_OILRIG
);
4173 if (st
->industry
!= nullptr && st
->industry
->neutral_station
== st
) {
4174 /* Don't leave dangling neutral station pointer */
4175 st
->industry
->neutral_station
= nullptr;
4180 static void ChangeTileOwner_Station(TileIndex tile
, Owner old_owner
, Owner new_owner
)
4182 if (IsRoadStopTile(tile
)) {
4183 FOR_ALL_ROADTRAMTYPES(rtt
) {
4184 /* Update all roadtypes, no matter if they are present */
4185 if (GetRoadOwner(tile
, rtt
) == old_owner
) {
4186 RoadType rt
= GetRoadType(tile
, rtt
);
4187 if (rt
!= INVALID_ROADTYPE
) {
4188 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4189 Company::Get(old_owner
)->infrastructure
.road
[rt
] -= 2;
4190 if (new_owner
!= INVALID_OWNER
) Company::Get(new_owner
)->infrastructure
.road
[rt
] += 2;
4192 SetRoadOwner(tile
, rtt
, new_owner
== INVALID_OWNER
? OWNER_NONE
: new_owner
);
4197 if (!IsTileOwner(tile
, old_owner
)) return;
4199 if (new_owner
!= INVALID_OWNER
) {
4200 /* Update company infrastructure counts. Only do it here
4201 * if the new owner is valid as otherwise the clear
4202 * command will do it for us. No need to dirty windows
4203 * here, we'll redraw the whole screen anyway.*/
4204 Company
*old_company
= Company::Get(old_owner
);
4205 Company
*new_company
= Company::Get(new_owner
);
4207 /* Update counts for underlying infrastructure. */
4208 switch (GetStationType(tile
)) {
4210 case STATION_WAYPOINT
:
4211 if (!IsStationTileBlocked(tile
)) {
4212 old_company
->infrastructure
.rail
[GetRailType(tile
)]--;
4213 new_company
->infrastructure
.rail
[GetRailType(tile
)]++;
4219 /* Road stops were already handled above. */
4224 if (GetWaterClass(tile
) == WATER_CLASS_CANAL
) {
4225 old_company
->infrastructure
.water
--;
4226 new_company
->infrastructure
.water
++;
4234 /* Update station tile count. */
4235 if (!IsBuoy(tile
) && !IsAirport(tile
)) {
4236 old_company
->infrastructure
.station
--;
4237 new_company
->infrastructure
.station
++;
4240 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4241 SetTileOwner(tile
, new_owner
);
4242 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
4244 if (IsDriveThroughStopTile(tile
)) {
4245 /* Remove the drive-through road stop */
4246 DoCommand(tile
, 1 | 1 << 8, (GetStationType(tile
) == STATION_TRUCK
) ? ROADSTOP_TRUCK
: ROADSTOP_BUS
, DC_EXEC
| DC_BANKRUPT
, CMD_REMOVE_ROAD_STOP
);
4247 assert(IsTileType(tile
, MP_ROAD
));
4248 /* Change owner of tile and all roadtypes */
4249 ChangeTileOwner(tile
, old_owner
, new_owner
);
4251 DoCommand(tile
, 0, 0, DC_EXEC
| DC_BANKRUPT
, CMD_LANDSCAPE_CLEAR
);
4252 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4253 * Update owner of buoy if it was not removed (was in orders).
4254 * Do not update when owned by OWNER_WATER (sea and rivers). */
4255 if ((IsTileType(tile
, MP_WATER
) || IsBuoyTile(tile
)) && IsTileOwner(tile
, old_owner
)) SetTileOwner(tile
, OWNER_NONE
);
4261 * Check if a drive-through road stop tile can be cleared.
4262 * Road stops built on town-owned roads check the conditions
4263 * that would allow clearing of the original road.
4264 * @param tile road stop tile to check
4265 * @param flags command flags
4266 * @return true if the road can be cleared
4268 static bool CanRemoveRoadWithStop(TileIndex tile
, DoCommandFlag flags
)
4270 /* Yeah... water can always remove stops, right? */
4271 if (_current_company
== OWNER_WATER
) return true;
4273 if (GetRoadTypeTram(tile
) != INVALID_ROADTYPE
) {
4274 Owner tram_owner
= GetRoadOwner(tile
, RTT_TRAM
);
4275 if (tram_owner
!= OWNER_NONE
&& CheckOwnership(tram_owner
).Failed()) return false;
4277 if (GetRoadTypeRoad(tile
) != INVALID_ROADTYPE
) {
4278 Owner road_owner
= GetRoadOwner(tile
, RTT_ROAD
);
4279 if (road_owner
!= OWNER_TOWN
) {
4280 if (road_owner
!= OWNER_NONE
&& CheckOwnership(road_owner
).Failed()) return false;
4282 if (CheckAllowRemoveRoad(tile
, GetAnyRoadBits(tile
, RTT_ROAD
), OWNER_TOWN
, RTT_ROAD
, flags
).Failed()) return false;
4290 * Clear a single tile of a station.
4291 * @param tile The tile to clear.
4292 * @param flags The DoCommand flags related to the "command".
4293 * @return The cost, or error of clearing.
4295 CommandCost
ClearTile_Station(TileIndex tile
, DoCommandFlag flags
)
4297 if (flags
& DC_AUTO
) {
4298 switch (GetStationType(tile
)) {
4300 case STATION_RAIL
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_RAILROAD
);
4301 case STATION_WAYPOINT
: return_cmd_error(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED
);
4302 case STATION_AIRPORT
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST
);
4303 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
);
4304 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
);
4305 case STATION_BUOY
: return_cmd_error(STR_ERROR_BUOY_IN_THE_WAY
);
4306 case STATION_DOCK
: return_cmd_error(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST
);
4307 case STATION_OILRIG
:
4308 SetDParam(1, STR_INDUSTRY_NAME_OIL_RIG
);
4309 return_cmd_error(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY
);
4313 switch (GetStationType(tile
)) {
4314 case STATION_RAIL
: return RemoveRailStation(tile
, flags
);
4315 case STATION_WAYPOINT
: return RemoveRailWaypoint(tile
, flags
);
4316 case STATION_AIRPORT
: return RemoveAirport(tile
, flags
);
4318 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4319 return_cmd_error(STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST
);
4321 return RemoveRoadStop(tile
, flags
);
4323 if (IsDriveThroughStopTile(tile
) && !CanRemoveRoadWithStop(tile
, flags
)) {
4324 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST
);
4326 return RemoveRoadStop(tile
, flags
);
4327 case STATION_BUOY
: return RemoveBuoy(tile
, flags
);
4328 case STATION_DOCK
: return RemoveDock(tile
, flags
);
4335 static CommandCost
TerraformTile_Station(TileIndex tile
, DoCommandFlag flags
, int z_new
, Slope tileh_new
)
4337 if (_settings_game
.construction
.build_on_slopes
&& AutoslopeEnabled()) {
4338 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4339 * TTDP does not call it.
4341 if (GetTileMaxZ(tile
) == z_new
+ GetSlopeMaxZ(tileh_new
)) {
4342 switch (GetStationType(tile
)) {
4343 case STATION_WAYPOINT
:
4344 case STATION_RAIL
: {
4345 DiagDirection direction
= AxisToDiagDir(GetRailStationAxis(tile
));
4346 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4347 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4348 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4351 case STATION_AIRPORT
:
4352 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4356 DiagDirection direction
= GetRoadStopDir(tile
);
4357 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, direction
)) break;
4358 if (IsDriveThroughStopTile(tile
)) {
4359 if (!AutoslopeCheckForEntranceEdge(tile
, z_new
, tileh_new
, ReverseDiagDir(direction
))) break;
4361 return CommandCost(EXPENSES_CONSTRUCTION
, _price
[PR_BUILD_FOUNDATION
]);
4368 return DoCommand(tile
, 0, 0, flags
, CMD_LANDSCAPE_CLEAR
);
4372 * Get flow for a station.
4373 * @param st Station to get flow for.
4374 * @return Flow for st.
4376 uint
FlowStat::GetShare(StationID st
) const
4379 for (SharesMap::const_iterator it
= this->shares
.begin(); it
!= this->shares
.end(); ++it
) {
4380 if (it
->second
== st
) {
4381 return it
->first
- prev
;
4390 * Get a station a package can be routed to, but exclude the given ones.
4391 * @param excluded StationID not to be selected.
4392 * @param excluded2 Another StationID not to be selected.
4393 * @return A station ID from the shares map.
4395 StationID
FlowStat::GetVia(StationID excluded
, StationID excluded2
) const
4397 if (this->unrestricted
== 0) return INVALID_STATION
;
4398 assert(!this->shares
.empty());
4399 SharesMap::const_iterator it
= this->shares
.upper_bound(RandomRange(this->unrestricted
));
4400 assert(it
!= this->shares
.end() && it
->first
<= this->unrestricted
);
4401 if (it
->second
!= excluded
&& it
->second
!= excluded2
) return it
->second
;
4403 /* We've hit one of the excluded stations.
4404 * Draw another share, from outside its range. */
4406 uint end
= it
->first
;
4407 uint begin
= (it
== this->shares
.begin() ? 0 : (--it
)->first
);
4408 uint interval
= end
- begin
;
4409 if (interval
>= this->unrestricted
) return INVALID_STATION
; // Only one station in the map.
4410 uint new_max
= this->unrestricted
- interval
;
4411 uint rand
= RandomRange(new_max
);
4412 SharesMap::const_iterator it2
= (rand
< begin
) ? this->shares
.upper_bound(rand
) :
4413 this->shares
.upper_bound(rand
+ interval
);
4414 assert(it2
!= this->shares
.end() && it2
->first
<= this->unrestricted
);
4415 if (it2
->second
!= excluded
&& it2
->second
!= excluded2
) return it2
->second
;
4417 /* We've hit the second excluded station.
4418 * Same as before, only a bit more complicated. */
4420 uint end2
= it2
->first
;
4421 uint begin2
= (it2
== this->shares
.begin() ? 0 : (--it2
)->first
);
4422 uint interval2
= end2
- begin2
;
4423 if (interval2
>= new_max
) return INVALID_STATION
; // Only the two excluded stations in the map.
4424 new_max
-= interval2
;
4425 if (begin
> begin2
) {
4426 Swap(begin
, begin2
);
4428 Swap(interval
, interval2
);
4430 rand
= RandomRange(new_max
);
4431 SharesMap::const_iterator it3
= this->shares
.upper_bound(this->unrestricted
);
4433 it3
= this->shares
.upper_bound(rand
);
4434 } else if (rand
< begin2
- interval
) {
4435 it3
= this->shares
.upper_bound(rand
+ interval
);
4437 it3
= this->shares
.upper_bound(rand
+ interval
+ interval2
);
4439 assert(it3
!= this->shares
.end() && it3
->first
<= this->unrestricted
);
4444 * Reduce all flows to minimum capacity so that they don't get in the way of
4445 * link usage statistics too much. Keep them around, though, to continue
4446 * routing any remaining cargo.
4448 void FlowStat::Invalidate()
4450 assert(!this->shares
.empty());
4451 SharesMap new_shares
;
4453 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4454 new_shares
[++i
] = it
->second
;
4455 if (it
->first
== this->unrestricted
) this->unrestricted
= i
;
4457 this->shares
.swap(new_shares
);
4458 assert(!this->shares
.empty() && this->unrestricted
<= (--this->shares
.end())->first
);
4462 * Change share for specified station. By specifying INT_MIN as parameter you
4463 * can erase a share. Newly added flows will be unrestricted.
4464 * @param st Next Hop to be removed.
4465 * @param flow Share to be added or removed.
4467 void FlowStat::ChangeShare(StationID st
, int flow
)
4469 /* We assert only before changing as afterwards the shares can actually
4470 * be empty. In that case the whole flow stat must be deleted then. */
4471 assert(!this->shares
.empty());
4473 uint removed_shares
= 0;
4474 uint added_shares
= 0;
4475 uint last_share
= 0;
4476 SharesMap new_shares
;
4477 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4478 if (it
->second
== st
) {
4480 uint share
= it
->first
- last_share
;
4481 if (flow
== INT_MIN
|| (uint
)(-flow
) >= share
) {
4482 removed_shares
+= share
;
4483 if (it
->first
<= this->unrestricted
) this->unrestricted
-= share
;
4484 if (flow
!= INT_MIN
) flow
+= share
;
4485 last_share
= it
->first
;
4486 continue; // remove the whole share
4488 removed_shares
+= (uint
)(-flow
);
4490 added_shares
+= (uint
)(flow
);
4492 if (it
->first
<= this->unrestricted
) this->unrestricted
+= flow
;
4494 /* If we don't continue above the whole flow has been added or
4498 new_shares
[it
->first
+ added_shares
- removed_shares
] = it
->second
;
4499 last_share
= it
->first
;
4502 new_shares
[last_share
+ (uint
)flow
] = st
;
4503 if (this->unrestricted
< last_share
) {
4504 this->ReleaseShare(st
);
4506 this->unrestricted
+= flow
;
4509 this->shares
.swap(new_shares
);
4513 * Restrict a flow by moving it to the end of the map and decreasing the amount
4514 * of unrestricted flow.
4515 * @param st Station of flow to be restricted.
4517 void FlowStat::RestrictShare(StationID st
)
4519 assert(!this->shares
.empty());
4521 uint last_share
= 0;
4522 SharesMap new_shares
;
4523 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4525 if (it
->first
> this->unrestricted
) return; // Not present or already restricted.
4526 if (it
->second
== st
) {
4527 flow
= it
->first
- last_share
;
4528 this->unrestricted
-= flow
;
4530 new_shares
[it
->first
] = it
->second
;
4533 new_shares
[it
->first
- flow
] = it
->second
;
4535 last_share
= it
->first
;
4537 if (flow
== 0) return;
4538 new_shares
[last_share
+ flow
] = st
;
4539 this->shares
.swap(new_shares
);
4540 assert(!this->shares
.empty());
4544 * Release ("unrestrict") a flow by moving it to the begin of the map and
4545 * increasing the amount of unrestricted flow.
4546 * @param st Station of flow to be released.
4548 void FlowStat::ReleaseShare(StationID st
)
4550 assert(!this->shares
.empty());
4552 uint next_share
= 0;
4554 for (SharesMap::reverse_iterator
it(this->shares
.rbegin()); it
!= this->shares
.rend(); ++it
) {
4555 if (it
->first
< this->unrestricted
) return; // Note: not <= as the share may hit the limit.
4557 flow
= next_share
- it
->first
;
4558 this->unrestricted
+= flow
;
4561 if (it
->first
== this->unrestricted
) return; // !found -> Limit not hit.
4562 if (it
->second
== st
) found
= true;
4564 next_share
= it
->first
;
4566 if (flow
== 0) return;
4567 SharesMap new_shares
;
4568 new_shares
[flow
] = st
;
4569 for (SharesMap::iterator
it(this->shares
.begin()); it
!= this->shares
.end(); ++it
) {
4570 if (it
->second
!= st
) {
4571 new_shares
[flow
+ it
->first
] = it
->second
;
4576 this->shares
.swap(new_shares
);
4577 assert(!this->shares
.empty());
4581 * Scale all shares from link graph's runtime to monthly values.
4582 * @param runtime Time the link graph has been running without compression.
4583 * @pre runtime must be greater than 0 as we don't want infinite flow values.
4585 void FlowStat::ScaleToMonthly(uint runtime
)
4587 assert(runtime
> 0);
4588 SharesMap new_shares
;
4590 for (SharesMap::iterator i
= this->shares
.begin(); i
!= this->shares
.end(); ++i
) {
4591 share
= max(share
+ 1, i
->first
* 30 / runtime
);
4592 new_shares
[share
] = i
->second
;
4593 if (this->unrestricted
== i
->first
) this->unrestricted
= share
;
4595 this->shares
.swap(new_shares
);
4599 * Add some flow from "origin", going via "via".
4600 * @param origin Origin of the flow.
4601 * @param via Next hop.
4602 * @param flow Amount of flow to be added.
4604 void FlowStatMap::AddFlow(StationID origin
, StationID via
, uint flow
)
4606 FlowStatMap::iterator origin_it
= this->find(origin
);
4607 if (origin_it
== this->end()) {
4608 this->insert(std::make_pair(origin
, FlowStat(via
, flow
)));
4610 origin_it
->second
.ChangeShare(via
, flow
);
4611 assert(!origin_it
->second
.GetShares()->empty());
4616 * Pass on some flow, remembering it as invalid, for later subtraction from
4617 * locally consumed flow. This is necessary because we can't have negative
4618 * flows and we don't want to sort the flows before adding them up.
4619 * @param origin Origin of the flow.
4620 * @param via Next hop.
4621 * @param flow Amount of flow to be passed.
4623 void FlowStatMap::PassOnFlow(StationID origin
, StationID via
, uint flow
)
4625 FlowStatMap::iterator prev_it
= this->find(origin
);
4626 if (prev_it
== this->end()) {
4627 FlowStat
fs(via
, flow
);
4628 fs
.AppendShare(INVALID_STATION
, flow
);
4629 this->insert(std::make_pair(origin
, fs
));
4631 prev_it
->second
.ChangeShare(via
, flow
);
4632 prev_it
->second
.ChangeShare(INVALID_STATION
, flow
);
4633 assert(!prev_it
->second
.GetShares()->empty());
4638 * Subtract invalid flows from locally consumed flow.
4639 * @param self ID of own station.
4641 void FlowStatMap::FinalizeLocalConsumption(StationID self
)
4643 for (FlowStatMap::iterator i
= this->begin(); i
!= this->end(); ++i
) {
4644 FlowStat
&fs
= i
->second
;
4645 uint local
= fs
.GetShare(INVALID_STATION
);
4646 if (local
> INT_MAX
) { // make sure it fits in an int
4647 fs
.ChangeShare(self
, -INT_MAX
);
4648 fs
.ChangeShare(INVALID_STATION
, -INT_MAX
);
4651 fs
.ChangeShare(self
, -(int)local
);
4652 fs
.ChangeShare(INVALID_STATION
, -(int)local
);
4654 /* If the local share is used up there must be a share for some
4655 * remote station. */
4656 assert(!fs
.GetShares()->empty());
4661 * Delete all flows at a station for specific cargo and destination.
4662 * @param via Remote station of flows to be deleted.
4663 * @return IDs of source stations for which the complete FlowStat, not only a
4664 * share, has been erased.
4666 StationIDStack
FlowStatMap::DeleteFlows(StationID via
)
4669 for (FlowStatMap::iterator f_it
= this->begin(); f_it
!= this->end();) {
4670 FlowStat
&s_flows
= f_it
->second
;
4671 s_flows
.ChangeShare(via
, INT_MIN
);
4672 if (s_flows
.GetShares()->empty()) {
4673 ret
.Push(f_it
->first
);
4674 this->erase(f_it
++);
4683 * Restrict all flows at a station for specific cargo and destination.
4684 * @param via Remote station of flows to be restricted.
4686 void FlowStatMap::RestrictFlows(StationID via
)
4688 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4689 it
->second
.RestrictShare(via
);
4694 * Release all flows at a station for specific cargo and destination.
4695 * @param via Remote station of flows to be released.
4697 void FlowStatMap::ReleaseFlows(StationID via
)
4699 for (FlowStatMap::iterator it
= this->begin(); it
!= this->end(); ++it
) {
4700 it
->second
.ReleaseShare(via
);
4705 * Get the sum of all flows from this FlowStatMap.
4706 * @return sum of all flows.
4708 uint
FlowStatMap::GetFlow() const
4711 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4712 ret
+= (--(i
->second
.GetShares()->end()))->first
;
4718 * Get the sum of flows via a specific station from this FlowStatMap.
4719 * @param via Remote station to look for.
4720 * @return all flows for 'via' added up.
4722 uint
FlowStatMap::GetFlowVia(StationID via
) const
4725 for (FlowStatMap::const_iterator i
= this->begin(); i
!= this->end(); ++i
) {
4726 ret
+= i
->second
.GetShare(via
);
4732 * Get the sum of flows from a specific station from this FlowStatMap.
4733 * @param from Origin station to look for.
4734 * @return all flows from 'from' added up.
4736 uint
FlowStatMap::GetFlowFrom(StationID from
) const
4738 FlowStatMap::const_iterator i
= this->find(from
);
4739 if (i
== this->end()) return 0;
4740 return (--(i
->second
.GetShares()->end()))->first
;
4744 * Get the flow from a specific station via a specific other station.
4745 * @param from Origin station to look for.
4746 * @param via Remote station to look for.
4747 * @return flow share originating at 'from' and going to 'via'.
4749 uint
FlowStatMap::GetFlowFromVia(StationID from
, StationID via
) const
4751 FlowStatMap::const_iterator i
= this->find(from
);
4752 if (i
== this->end()) return 0;
4753 return i
->second
.GetShare(via
);
4756 extern const TileTypeProcs _tile_type_station_procs
= {
4757 DrawTile_Station
, // draw_tile_proc
4758 GetSlopePixelZ_Station
, // get_slope_z_proc
4759 ClearTile_Station
, // clear_tile_proc
4760 nullptr, // add_accepted_cargo_proc
4761 GetTileDesc_Station
, // get_tile_desc_proc
4762 GetTileTrackStatus_Station
, // get_tile_track_status_proc
4763 ClickTile_Station
, // click_tile_proc
4764 AnimateTile_Station
, // animate_tile_proc
4765 TileLoop_Station
, // tile_loop_proc
4766 ChangeTileOwner_Station
, // change_tile_owner_proc
4767 nullptr, // add_produced_cargo_proc
4768 VehicleEnter_Station
, // vehicle_enter_tile_proc
4769 GetFoundation_Station
, // get_foundation_proc
4770 TerraformTile_Station
, // terraform_tile_proc