4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file station.cpp Implementation of the station base class. */
13 #include "company_func.h"
14 #include "company_base.h"
16 #include "viewport_func.h"
17 #include "date_func.h"
18 #include "command_func.h"
19 #include "news_func.h"
21 #include "vehiclelist.h"
22 #include "core/pool_func.hpp"
23 #include "station_base.h"
24 #include "roadstop_base.h"
25 #include "dock_base.h"
27 #include "core/random_func.hpp"
28 #include "overlay_cmd.h"
29 #include "linkgraph/linkgraph.h"
30 #include "linkgraph/linkgraphschedule.h"
31 #include "tracerestrict.h"
33 #include "table/strings.h"
35 #include "safeguards.h"
37 /** The pool of stations. */
38 StationPool
_station_pool("Station");
39 INSTANTIATE_POOL_METHODS(Station
)
41 typedef StationIDStack::SmallStackPool StationIDStackPool
;
42 template<> StationIDStackPool
StationIDStack::_pool
= StationIDStackPool();
44 BaseStation::~BaseStation()
49 if (CleaningPool()) return;
51 DeleteWindowById(WC_TRAINS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_TRAIN
, this->owner
, this->index
).Pack());
52 DeleteWindowById(WC_ROADVEH_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_ROAD
, this->owner
, this->index
).Pack());
53 DeleteWindowById(WC_SHIPS_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_SHIP
, this->owner
, this->index
).Pack());
54 DeleteWindowById(WC_AIRCRAFT_LIST
, VehicleListIdentifier(VL_STATION_LIST
, VEH_AIRCRAFT
, this->owner
, this->index
).Pack());
55 DeleteWindowById(WC_DEPARTURES_BOARD
, this->index
);
57 this->sign
.MarkDirty();
60 Station::Station(TileIndex tile
) :
61 SpecializedStation
<Station
, false>(tile
),
62 bus_station(INVALID_TILE
, 0, 0),
63 truck_station(INVALID_TILE
, 0, 0),
64 dock_station(INVALID_TILE
, 0, 0),
67 time_since_unload(255),
68 last_vehicle_type(VEH_INVALID
)
70 /* this->random_bits is set in Station::AddFacility() */
74 * Clean up a station by clearing vehicle orders, invalidating windows and
75 * removing link stats.
76 * Aircraft-Hangar orders need special treatment here, as the hangars are
77 * actually part of a station (tiletype is STATION), but the order type
83 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
84 this->goods
[c
].cargo
.OnCleanPool();
89 while (!this->loading_vehicles
.empty()) {
90 this->loading_vehicles
.front()->LeaveStation();
95 if (!a
->IsNormalAircraft()) continue;
96 if (a
->targetairport
== this->index
) a
->targetairport
= INVALID_STATION
;
99 for (CargoID c
= 0; c
< NUM_CARGO
; ++c
) {
100 LinkGraph
*lg
= LinkGraph::GetIfValid(this->goods
[c
].link_graph
);
101 if (lg
== NULL
) continue;
103 for (NodeID node
= 0; node
< lg
->Size(); ++node
) {
104 Station
*st
= Station::Get((*lg
)[node
].Station());
105 st
->goods
[c
].flows
.erase(this->index
);
106 if ((*lg
)[node
][this->goods
[c
].node
].LastUpdate() != INVALID_DATE
) {
107 st
->goods
[c
].flows
.DeleteFlows(this->index
);
108 RerouteCargo(st
, c
, this->index
, st
->index
);
111 lg
->RemoveNode(this->goods
[c
].node
);
112 if (lg
->Size() == 0) {
113 LinkGraphSchedule::instance
.Unqueue(lg
);
119 FOR_ALL_VEHICLES(v
) {
120 /* Forget about this station if this station is removed */
121 if (v
->last_station_visited
== this->index
) {
122 v
->last_station_visited
= INVALID_STATION
;
124 if (v
->last_loading_station
== this->index
) {
125 v
->last_loading_station
= INVALID_STATION
;
129 /* Clear the persistent storage. */
130 delete this->airport
.psa
;
132 if (this->owner
== OWNER_NONE
) {
133 /* Invalidate all in case of oil rigs. */
134 InvalidateWindowClassesData(WC_STATION_LIST
, 0);
136 InvalidateWindowData(WC_STATION_LIST
, this->owner
, 0);
139 if (Overlays::Instance()->HasStation(Station::Get(this->index
))) {
140 Overlays::Instance()->ToggleStation(Station::Get(this->index
));
143 DeleteWindowById(WC_STATION_VIEW
, index
);
145 /* Now delete all orders that go to the station */
146 RemoveOrderFromAllVehicles(OT_GOTO_STATION
, this->index
);
148 TraceRestrictRemoveDestinationID(TROCAF_STATION
, this->index
);
150 /* Remove all news items */
151 DeleteStationNews(this->index
);
153 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
154 this->goods
[c
].cargo
.Truncate();
157 CargoPacket::InvalidateAllFrom(this->index
);
161 * Evaluate if a tile is in station catchment area.
162 * @param ti the tile info
163 * @param type the catchment type of the station
164 * @return true/false if the tile is in catchment
166 bool Station::IsTileInCatchmentArea(const TileInfo
* ti
, CatchmentType type
) const
170 return this->rect
.PtInExtendedRect(TileX(ti
->tile
),TileY(ti
->tile
),this->GetCatchmentRadius());
172 return this->catchment
.IsTileInCatchment(ti
->tile
);
182 * Invalidating of the JoinStation window has to be done
183 * after removing item from the pool.
184 * @param index index of deleted item
186 void BaseStation::PostDestructor(size_t index
)
188 InvalidateWindowData(WC_SELECT_STATION
, 0, 0);
192 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
193 * @param v the vehicle to get the first road stop for
194 * @return the first roadstop that this vehicle can load at
196 RoadStop
*Station::GetPrimaryRoadStop(const RoadVehicle
*v
) const
198 RoadStop
*rs
= this->GetPrimaryRoadStop(v
->IsBus() ? ROADSTOP_BUS
: ROADSTOP_TRUCK
);
200 for (; rs
!= NULL
; rs
= rs
->next
) {
201 /* The vehicle cannot go to this roadstop (different roadtype) */
202 if ((GetRoadTypes(rs
->xy
) & v
->compatible_roadtypes
) == ROADTYPES_NONE
) continue;
203 /* The vehicle is articulated and can therefore not go to a standard road stop. */
204 if (IsStandardRoadStopTile(rs
->xy
) && v
->HasArticulatedPart()) continue;
206 /* The vehicle can actually go to this road stop. So, return it! */
214 * Called when new facility is built on the station. If it is the first facility
215 * it initializes also 'xy' and 'random_bits' members
217 void Station::AddFacility(StationFacility new_facility_bit
, TileIndex facil_xy
)
219 if (this->facilities
== FACIL_NONE
) {
221 this->random_bits
= Random();
223 this->facilities
|= new_facility_bit
;
224 this->owner
= _current_company
;
225 this->build_date
= _date
;
229 * Marks the tiles of the station as dirty.
233 void Station::MarkTilesDirty(bool cargo_change
) const
235 TileIndex tile
= this->train_station
.tile
;
238 if (tile
== INVALID_TILE
) return;
240 /* cargo_change is set if we're refreshing the tiles due to cargo moving
243 /* Don't waste time updating if there are no custom station graphics
244 * that might change. Even if there are custom graphics, they might
245 * not change. Unfortunately we have no way of telling. */
246 if (this->num_specs
== 0) return;
249 for (h
= 0; h
< train_station
.h
; h
++) {
250 for (w
= 0; w
< train_station
.w
; w
++) {
251 if (this->TileBelongsToRailStation(tile
)) {
252 MarkTileDirtyByTile(tile
, ZOOM_LVL_DRAW_MAP
);
254 tile
+= TileDiffXY(1, 0);
256 tile
+= TileDiffXY(-w
, 1);
261 * Marks the acceptance tiles of the station as dirty.
265 void Station::MarkAcceptanceTilesDirty() const
267 Rect rec
= this->GetCatchmentRect();
268 TileIndex top_left
= TileXY(rec
.left
, rec
.top
);
269 int width
= rec
.right
- rec
.left
+ 1;
270 int height
= rec
.bottom
- rec
.top
+ 1;
272 TILE_AREA_LOOP(tile
, TileArea(top_left
, width
, height
) ) {
273 MarkTileDirtyByTile(tile
);
277 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
) const
279 assert(this->TileBelongsToRailStation(tile
));
281 TileIndexDiff delta
= (GetRailStationAxis(tile
) == AXIS_X
? TileDiffXY(1, 0) : TileDiffXY(0, 1));
288 } while (IsCompatibleTrainStationTile(t
, tile
));
294 } while (IsCompatibleTrainStationTile(t
, tile
));
299 /* virtual */ uint
Station::GetPlatformLength(TileIndex tile
, DiagDirection dir
) const
301 TileIndex start_tile
= tile
;
303 assert(IsRailStationTile(tile
));
304 assert(dir
< DIAGDIR_END
);
308 tile
+= TileOffsByDiagDir(dir
);
309 } while (IsCompatibleTrainStationTile(tile
, start_tile
));
315 * Determines the catchment radius of the station
318 uint
Station::GetCatchmentRadius() const
322 if (_settings_game
.station
.modified_catchment
) {
323 if (this->bus_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_BUS
);
324 if (this->truck_stops
!= NULL
) ret
= max
<uint
>(ret
, CA_TRUCK
);
325 if (this->train_station
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, CA_TRAIN
);
326 if (this->docks
!= NULL
) ret
= max
<uint
>(ret
, CA_DOCK
);
327 if (this->airport
.tile
!= INVALID_TILE
) ret
= max
<uint
>(ret
, this->airport
.GetSpec()->catchment
);
329 if (this->bus_stops
!= NULL
|| this->truck_stops
!= NULL
|| this->train_station
.tile
!= INVALID_TILE
|| this->docks
!= NULL
|| this->airport
.tile
!= INVALID_TILE
) {
338 * Determines catchment rectangle of this station
339 * @return clamped catchment rectangle
341 Rect
Station::GetCatchmentRectUsingRadius(uint catchment_radius
) const
343 assert(!this->rect
.IsEmpty());
345 /* Compute acceptance rectangle */
347 max
<int>(this->rect
.left
- catchment_radius
, 0),
348 max
<int>(this->rect
.top
- catchment_radius
, 0),
349 min
<int>(this->rect
.right
+ catchment_radius
, MapMaxX()),
350 min
<int>(this->rect
.bottom
+ catchment_radius
, MapMaxY())
356 /** Rect and pointer to IndustryVector */
357 struct RectAndIndustryVector
{
358 Rect rect
; ///< The rectangle to search the industries in.
359 IndustryVector
*industries_near
; ///< The nearby industries.
363 * Callback function for Station::RecomputeIndustriesNear()
364 * Tests whether tile is an industry and possibly adds
365 * the industry to station's industries_near list.
366 * @param ind_tile tile to check
367 * @param user_data pointer to RectAndIndustryVector
368 * @return always false, we want to search all tiles
370 static bool FindIndustryToDeliver(TileIndex ind_tile
, void *user_data
)
372 /* Only process industry tiles */
373 if (!IsTileType(ind_tile
, MP_INDUSTRY
)) return false;
375 RectAndIndustryVector
*riv
= (RectAndIndustryVector
*)user_data
;
376 Industry
*ind
= Industry::GetByTile(ind_tile
);
378 /* Don't check further if this industry is already in the list */
379 if (riv
->industries_near
->Contains(ind
)) return false;
381 /* Only process tiles in the station acceptance rectangle */
382 int x
= TileX(ind_tile
);
383 int y
= TileY(ind_tile
);
384 if (x
< riv
->rect
.left
|| x
> riv
->rect
.right
|| y
< riv
->rect
.top
|| y
> riv
->rect
.bottom
) return false;
386 /* Include only industries that can accept cargo */
388 for (cargo_index
= 0; cargo_index
< lengthof(ind
->accepts_cargo
); cargo_index
++) {
389 if (ind
->accepts_cargo
[cargo_index
] != CT_INVALID
) break;
391 if (cargo_index
>= lengthof(ind
->accepts_cargo
)) return false;
393 *riv
->industries_near
->Append() = ind
;
399 * Recomputes Station::industries_near, list of industries possibly
400 * accepting cargo in station's catchment radius
402 void Station::RecomputeIndustriesNear()
404 this->industries_near
.Clear();
405 if (this->rect
.IsEmpty()) return;
407 RectAndIndustryVector riv
= {
408 this->GetCatchmentRect(),
409 &this->industries_near
412 /* Compute maximum extent of acceptance rectangle wrt. station sign */
413 TileIndex start_tile
= this->xy
;
414 uint max_radius
= max(
415 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.left
, riv
.rect
.bottom
))),
416 max(DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.top
)), DistanceManhattan(start_tile
, TileXY(riv
.rect
.right
, riv
.rect
.bottom
)))
419 CircularTileSearch(&start_tile
, 2 * max_radius
+ 1, &FindIndustryToDeliver
, &riv
);
423 * Recomputes Station::industries_near for all stations
425 /* static */ void Station::RecomputeIndustriesNearForAll()
428 FOR_ALL_STATIONS(st
) st
->RecomputeIndustriesNear();
431 /************************************************************************/
432 /* StationRect implementation */
433 /************************************************************************/
435 StationRect::StationRect()
440 void StationRect::MakeEmpty()
442 this->left
= this->top
= this->right
= this->bottom
= 0;
446 * Determines whether a given point (x, y) is within a certain distance of
447 * the station rectangle.
448 * @note x and y are in Tile coordinates
449 * @param x X coordinate
450 * @param y Y coordinate
451 * @param distance The maximum distance a point may have (L1 norm)
452 * @return true if the point is within distance tiles of the station rectangle
454 bool StationRect::PtInExtendedRect(int x
, int y
, int distance
) const
456 return this->left
- distance
<= x
&& x
<= this->right
+ distance
&&
457 this->top
- distance
<= y
&& y
<= this->bottom
+ distance
;
460 bool StationRect::IsEmpty() const
462 return this->left
== 0 || this->left
> this->right
|| this->top
> this->bottom
;
465 CommandCost
StationRect::BeforeAddTile(TileIndex tile
, StationRectMode mode
)
469 if (this->IsEmpty()) {
470 /* we are adding the first station tile */
471 if (mode
!= ADD_TEST
) {
472 this->left
= this->right
= x
;
473 this->top
= this->bottom
= y
;
475 } else if (!this->PtInExtendedRect(x
, y
)) {
476 /* current rect is not empty and new point is outside this rect
477 * make new spread-out rectangle */
478 Rect new_rect
= {min(x
, this->left
), min(y
, this->top
), max(x
, this->right
), max(y
, this->bottom
)};
480 /* check new rect dimensions against preset max */
481 int w
= new_rect
.right
- new_rect
.left
+ 1;
482 int h
= new_rect
.bottom
- new_rect
.top
+ 1;
483 if (mode
!= ADD_FORCE
&& (w
> _settings_game
.station
.station_spread
|| h
> _settings_game
.station
.station_spread
)) {
484 assert(mode
!= ADD_TRY
);
485 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT
);
488 /* spread-out ok, return true */
489 if (mode
!= ADD_TEST
) {
490 /* we should update the station rect */
494 ; // new point is inside the rect, we don't need to do anything
496 return CommandCost();
499 CommandCost
StationRect::BeforeAddRect(TileIndex tile
, int w
, int h
, StationRectMode mode
)
501 if (mode
== ADD_FORCE
|| (w
<= _settings_game
.station
.station_spread
&& h
<= _settings_game
.station
.station_spread
)) {
502 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
503 CommandCost ret
= this->BeforeAddTile(tile
, mode
);
504 if (ret
.Succeeded()) ret
= this->BeforeAddTile(TILE_ADDXY(tile
, w
- 1, h
- 1), mode
);
507 return CommandCost();
511 * Check whether station tiles of the given station id exist in the given rectangle
512 * @param st_id Station ID to look for in the rectangle
513 * @param left_a Minimal tile X edge of the rectangle
514 * @param top_a Minimal tile Y edge of the rectangle
515 * @param right_a Maximal tile X edge of the rectangle (inclusive)
516 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
517 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
519 /* static */ bool StationRect::ScanForStationTiles(StationID st_id
, int left_a
, int top_a
, int right_a
, int bottom_a
)
521 TileArea
ta(TileXY(left_a
, top_a
), TileXY(right_a
, bottom_a
));
522 TILE_AREA_LOOP(tile
, ta
) {
523 if (IsTileType(tile
, MP_STATION
) && GetStationIndex(tile
) == st_id
) return true;
529 bool StationRect::AfterRemoveTile(BaseStation
*st
, TileIndex tile
)
534 /* look if removed tile was on the bounding rect edge
535 * and try to reduce the rect by this edge
536 * do it until we have empty rect or nothing to do */
538 /* check if removed tile is on rect edge */
539 bool left_edge
= (x
== this->left
);
540 bool right_edge
= (x
== this->right
);
541 bool top_edge
= (y
== this->top
);
542 bool bottom_edge
= (y
== this->bottom
);
544 /* can we reduce the rect in either direction? */
545 bool reduce_x
= ((left_edge
|| right_edge
) && !ScanForStationTiles(st
->index
, x
, this->top
, x
, this->bottom
));
546 bool reduce_y
= ((top_edge
|| bottom_edge
) && !ScanForStationTiles(st
->index
, this->left
, y
, this->right
, y
));
547 if (!(reduce_x
|| reduce_y
)) break; // nothing to do (can't reduce)
550 /* reduce horizontally */
552 /* move left edge right */
553 this->left
= x
= x
+ 1;
555 /* move right edge left */
556 this->right
= x
= x
- 1;
560 /* reduce vertically */
562 /* move top edge down */
563 this->top
= y
= y
+ 1;
565 /* move bottom edge up */
566 this->bottom
= y
= y
- 1;
570 if (left
> right
|| top
> bottom
) {
571 /* can't continue, if the remaining rectangle is empty */
573 return true; // empty remaining rect
576 return false; // non-empty remaining rect
579 bool StationRect::AfterRemoveRect(BaseStation
*st
, TileArea ta
)
581 assert(this->PtInExtendedRect(TileX(ta
.tile
), TileY(ta
.tile
)));
582 assert(this->PtInExtendedRect(TileX(ta
.tile
) + ta
.w
- 1, TileY(ta
.tile
) + ta
.h
- 1));
584 bool empty
= this->AfterRemoveTile(st
, ta
.tile
);
585 if (ta
.w
!= 1 || ta
.h
!= 1) empty
= empty
|| this->AfterRemoveTile(st
, TILE_ADDXY(ta
.tile
, ta
.w
- 1, ta
.h
- 1));
589 StationRect
& StationRect::operator = (const Rect
&src
)
591 this->left
= src
.left
;
593 this->right
= src
.right
;
594 this->bottom
= src
.bottom
;
599 * Calculates the maintenance cost of all airports of a company.
600 * @param owner Company.
601 * @return Total cost.
603 Money
AirportMaintenanceCost(Owner owner
)
605 Money total_cost
= 0;
608 FOR_ALL_STATIONS(st
) {
609 if (st
->owner
== owner
&& (st
->facilities
& FACIL_AIRPORT
)) {
610 total_cost
+= _price
[PR_INFRASTRUCTURE_AIRPORT
] * st
->airport
.GetSpec()->maintenance_cost
;
613 /* 3 bits fraction for the maintenance cost factor. */
614 return total_cost
>> 3;
617 /************************************************************************/
618 /* StationCatchment implementation */
619 /************************************************************************/
621 StationCatchment::StationCatchment()
626 * Determines whether a given point (x, y) is within the station catchment area
627 * @param tile TileIndex to test
628 * @return true if the point is within the station catchment area
630 bool StationCatchment::IsTileInCatchment(TileIndex tile
) const
632 return this->catchmentTiles
.find(tile
) != this->catchmentTiles
.end();
635 bool StationCatchment::IsEmpty() const
637 return this->catchmentTiles
.empty();
640 void StationCatchment::BeforeAddTile(TileIndex tile
, uint catchmentRadius
)
644 TileIndex top_left
= TileXY(max
<int>(x
- catchmentRadius
,0),max
<int>(y
- catchmentRadius
, 0));
645 int w
= min
<int>(x
+ catchmentRadius
, MapMaxX()) - TileX(top_left
) + 1;
646 int h
= min
<int>(y
+ catchmentRadius
, MapMaxY()) - TileY(top_left
) + 1;
648 /* we are adding the first station tile */
649 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
) ) {
650 std::set
<TileIndex
> fromSet
;
651 fromSet
.insert(tile
);
652 this->catchmentTiles
[t
] = fromSet
;
655 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
) ) {
656 std::map
<TileIndex
, std::set
<TileIndex
> >::iterator found
= this->catchmentTiles
.find(t
);
657 if ( found
== this->catchmentTiles
.end()) {
658 std::set
<TileIndex
> fromSet
;
659 fromSet
.insert(tile
);
660 this->catchmentTiles
[t
] = fromSet
;
661 } else if ((*found
).second
.find(tile
) == (*found
).second
.end()) {
662 (*found
).second
.insert(tile
);
668 void StationCatchment::BeforeAddRect(TileIndex tile
, int w
, int h
, uint catchmentRadius
)
670 TILE_AREA_LOOP(t
, TileArea(tile
, w
, h
) ) {
671 this->BeforeAddTile(t
, catchmentRadius
);
675 void StationCatchment::AfterRemoveTile(TileIndex tile
, uint catchmentRadius
)
679 TileIndex top_left
= TileXY(max
<int>(x
- catchmentRadius
,0),max
<int>(y
- catchmentRadius
, 0));
680 int w
= min
<int>(x
+ catchmentRadius
, MapMaxX()) - TileX(top_left
) + 1;
681 int h
= min
<int>(y
+ catchmentRadius
, MapMaxY()) - TileY(top_left
) + 1;
682 TILE_AREA_LOOP(t
, TileArea(top_left
, w
, h
)) {
683 std::map
<TileIndex
, std::set
<TileIndex
> >::iterator found
= this->catchmentTiles
.find(t
);
684 assert(found
!= this->catchmentTiles
.end());
685 std::set
<TileIndex
>::iterator stTileIter
= (*found
).second
.find(tile
);
686 assert(stTileIter
!= (*found
).second
.end());
687 (*found
).second
.erase(stTileIter
);
688 if ((*found
).second
.empty()) {
689 // tile t is no longer in StationCatchment
690 this->catchmentTiles
.erase(found
);
695 void StationCatchment::AfterRemoveRect(TileIndex tile
, int w
, int h
, uint catchmentRadius
)
697 TILE_AREA_LOOP(t
, TileArea(tile
, w
, h
)) {
698 this->AfterRemoveTile(t
, catchmentRadius
);