Feature: Hide block signals in GUI by default (#8688)
[openttd-github.git] / src / station.cpp
blob877f53d4e0aa9fcd27f2a7ec39f2dc88299284a6
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file station.cpp Implementation of the station base class. */
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "company_base.h"
13 #include "roadveh.h"
14 #include "viewport_func.h"
15 #include "viewport_kdtree.h"
16 #include "date_func.h"
17 #include "command_func.h"
18 #include "news_func.h"
19 #include "aircraft.h"
20 #include "vehiclelist.h"
21 #include "core/pool_func.hpp"
22 #include "station_base.h"
23 #include "station_kdtree.h"
24 #include "roadstop_base.h"
25 #include "industry.h"
26 #include "town.h"
27 #include "core/random_func.hpp"
28 #include "linkgraph/linkgraph.h"
29 #include "linkgraph/linkgraphschedule.h"
31 #include "table/strings.h"
33 #include "safeguards.h"
35 /** The pool of stations. */
36 StationPool _station_pool("Station");
37 INSTANTIATE_POOL_METHODS(Station)
40 StationKdtree _station_kdtree(Kdtree_StationXYFunc);
42 void RebuildStationKdtree()
44 std::vector<StationID> stids;
45 for (const Station *st : Station::Iterate()) {
46 stids.push_back(st->index);
48 _station_kdtree.Build(stids.begin(), stids.end());
52 BaseStation::~BaseStation()
54 free(this->speclist);
56 if (CleaningPool()) return;
58 CloseWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->index).Pack());
59 CloseWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->index).Pack());
60 CloseWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->index).Pack());
61 CloseWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->index).Pack());
63 this->sign.MarkDirty();
66 Station::Station(TileIndex tile) :
67 SpecializedStation<Station, false>(tile),
68 bus_station(INVALID_TILE, 0, 0),
69 truck_station(INVALID_TILE, 0, 0),
70 ship_station(INVALID_TILE, 0, 0),
71 indtype(IT_INVALID),
72 time_since_load(255),
73 time_since_unload(255),
74 last_vehicle_type(VEH_INVALID)
76 /* this->random_bits is set in Station::AddFacility() */
79 /**
80 * Clean up a station by clearing vehicle orders, invalidating windows and
81 * removing link stats.
82 * Aircraft-Hangar orders need special treatment here, as the hangars are
83 * actually part of a station (tiletype is STATION), but the order type
84 * is OT_GOTO_DEPOT.
86 Station::~Station()
88 if (CleaningPool()) {
89 for (CargoID c = 0; c < NUM_CARGO; c++) {
90 this->goods[c].cargo.OnCleanPool();
92 return;
95 while (!this->loading_vehicles.empty()) {
96 this->loading_vehicles.front()->LeaveStation();
99 for (Aircraft *a : Aircraft::Iterate()) {
100 if (!a->IsNormalAircraft()) continue;
101 if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
104 for (CargoID c = 0; c < NUM_CARGO; ++c) {
105 LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
106 if (lg == nullptr) continue;
108 for (NodeID node = 0; node < lg->Size(); ++node) {
109 Station *st = Station::Get((*lg)[node].Station());
110 st->goods[c].flows.erase(this->index);
111 if ((*lg)[node][this->goods[c].node].LastUpdate() != INVALID_DATE) {
112 st->goods[c].flows.DeleteFlows(this->index);
113 RerouteCargo(st, c, this->index, st->index);
116 lg->RemoveNode(this->goods[c].node);
117 if (lg->Size() == 0) {
118 LinkGraphSchedule::instance.Unqueue(lg);
119 delete lg;
123 for (Vehicle *v : Vehicle::Iterate()) {
124 /* Forget about this station if this station is removed */
125 if (v->last_station_visited == this->index) {
126 v->last_station_visited = INVALID_STATION;
128 if (v->last_loading_station == this->index) {
129 v->last_loading_station = INVALID_STATION;
133 /* Remove station from industries and towns that reference it. */
134 this->RemoveFromAllNearbyLists();
136 /* Clear the persistent storage. */
137 delete this->airport.psa;
139 if (this->owner == OWNER_NONE) {
140 /* Invalidate all in case of oil rigs. */
141 InvalidateWindowClassesData(WC_STATION_LIST, 0);
142 } else {
143 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
146 CloseWindowById(WC_STATION_VIEW, index);
148 /* Now delete all orders that go to the station */
149 RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
151 /* Remove all news items */
152 DeleteStationNews(this->index);
154 for (CargoID c = 0; c < NUM_CARGO; c++) {
155 this->goods[c].cargo.Truncate();
158 CargoPacket::InvalidateAllFrom(this->index);
160 _station_kdtree.Remove(this->index);
161 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
166 * Invalidating of the JoinStation window has to be done
167 * after removing item from the pool.
168 * @param index index of deleted item
170 void BaseStation::PostDestructor(size_t index)
172 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
176 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
177 * @param v the vehicle to get the first road stop for
178 * @return the first roadstop that this vehicle can load at
180 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
182 RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
184 for (; rs != nullptr; rs = rs->next) {
185 /* The vehicle cannot go to this roadstop (different roadtype) */
186 if (!HasTileAnyRoadType(rs->xy, v->compatible_roadtypes)) continue;
187 /* The vehicle is articulated and can therefore not go to a standard road stop. */
188 if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
190 /* The vehicle can actually go to this road stop. So, return it! */
191 break;
194 return rs;
198 * Called when new facility is built on the station. If it is the first facility
199 * it initializes also 'xy' and 'random_bits' members
201 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
203 if (this->facilities == FACIL_NONE) {
204 this->MoveSign(facil_xy);
205 this->random_bits = Random();
207 this->facilities |= new_facility_bit;
208 this->owner = _current_company;
209 this->build_date = _date;
213 * Marks the tiles of the station as dirty.
215 * @ingroup dirty
217 void Station::MarkTilesDirty(bool cargo_change) const
219 TileIndex tile = this->train_station.tile;
220 int w, h;
222 if (tile == INVALID_TILE) return;
224 /* cargo_change is set if we're refreshing the tiles due to cargo moving
225 * around. */
226 if (cargo_change) {
227 /* Don't waste time updating if there are no custom station graphics
228 * that might change. Even if there are custom graphics, they might
229 * not change. Unfortunately we have no way of telling. */
230 if (this->num_specs == 0) return;
233 for (h = 0; h < train_station.h; h++) {
234 for (w = 0; w < train_station.w; w++) {
235 if (this->TileBelongsToRailStation(tile)) {
236 MarkTileDirtyByTile(tile);
238 tile += TileDiffXY(1, 0);
240 tile += TileDiffXY(-w, 1);
244 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
246 assert(this->TileBelongsToRailStation(tile));
248 TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
250 TileIndex t = tile;
251 uint len = 0;
252 do {
253 t -= delta;
254 len++;
255 } while (IsCompatibleTrainStationTile(t, tile));
257 t = tile;
258 do {
259 t += delta;
260 len++;
261 } while (IsCompatibleTrainStationTile(t, tile));
263 return len - 1;
266 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
268 TileIndex start_tile = tile;
269 uint length = 0;
270 assert(IsRailStationTile(tile));
271 assert(dir < DIAGDIR_END);
273 do {
274 length++;
275 tile += TileOffsByDiagDir(dir);
276 } while (IsCompatibleTrainStationTile(tile, start_tile));
278 return length;
282 * Get the catchment size of an individual station tile.
283 * @param tile Station tile to get catchment size of.
284 * @param st Associated station of station tile.
285 * @pre IsTileType(tile, MP_STATION)
286 * @return The catchment size of the station tile.
288 static uint GetTileCatchmentRadius(TileIndex tile, const Station *st)
290 assert(IsTileType(tile, MP_STATION));
292 if (_settings_game.station.modified_catchment) {
293 switch (GetStationType(tile)) {
294 case STATION_RAIL: return CA_TRAIN;
295 case STATION_OILRIG: return CA_UNMODIFIED;
296 case STATION_AIRPORT: return st->airport.GetSpec()->catchment;
297 case STATION_TRUCK: return CA_TRUCK;
298 case STATION_BUS: return CA_BUS;
299 case STATION_DOCK: return CA_DOCK;
301 default: NOT_REACHED();
302 case STATION_BUOY:
303 case STATION_WAYPOINT: return CA_NONE;
305 } else {
306 switch (GetStationType(tile)) {
307 default: return CA_UNMODIFIED;
308 case STATION_BUOY:
309 case STATION_WAYPOINT: return CA_NONE;
315 * Determines the catchment radius of the station
316 * @return The radius
318 uint Station::GetCatchmentRadius() const
320 uint ret = CA_NONE;
322 if (_settings_game.station.modified_catchment) {
323 if (this->bus_stops != nullptr) ret = std::max<uint>(ret, CA_BUS);
324 if (this->truck_stops != nullptr) ret = std::max<uint>(ret, CA_TRUCK);
325 if (this->train_station.tile != INVALID_TILE) ret = std::max<uint>(ret, CA_TRAIN);
326 if (this->ship_station.tile != INVALID_TILE) ret = std::max<uint>(ret, CA_DOCK);
327 if (this->airport.tile != INVALID_TILE) ret = std::max<uint>(ret, this->airport.GetSpec()->catchment);
328 } else {
329 if (this->bus_stops != nullptr || this->truck_stops != nullptr || this->train_station.tile != INVALID_TILE || this->ship_station.tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
330 ret = CA_UNMODIFIED;
334 return ret;
338 * Determines catchment rectangle of this station
339 * @return clamped catchment rectangle
341 Rect Station::GetCatchmentRect() const
343 assert(!this->rect.IsEmpty());
345 /* Compute acceptance rectangle */
346 int catchment_radius = this->GetCatchmentRadius();
348 Rect ret = {
349 std::max<int>(this->rect.left - catchment_radius, 0),
350 std::max<int>(this->rect.top - catchment_radius, 0),
351 std::min<int>(this->rect.right + catchment_radius, MapMaxX()),
352 std::min<int>(this->rect.bottom + catchment_radius, MapMaxY())
355 return ret;
359 * Add nearby industry to station's industries_near list if it accepts cargo.
360 * @param ind Industry
362 void Station::AddIndustryToDeliver(Industry *ind)
364 /* Don't check further if this industry is already in the list */
365 if (this->industries_near.find(ind) != this->industries_near.end()) return;
367 /* Include only industries that can accept cargo */
368 uint cargo_index;
369 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
370 if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
372 if (cargo_index >= lengthof(ind->accepts_cargo)) return;
374 this->industries_near.insert(ind);
378 * Remove this station from the nearby stations lists of all towns and industries.
380 void Station::RemoveFromAllNearbyLists()
382 for (Town *t : Town::Iterate()) { t->stations_near.erase(this); }
383 for (Industry *i : Industry::Iterate()) { i->stations_near.erase(this); }
387 * Test if the given town ID is covered by our catchment area.
388 * This is used when removing a house tile to determine if it was the last house tile
389 * within our catchment.
390 * @param t TownID to test.
391 * @return true if at least one house tile of TownID is covered.
393 bool Station::CatchmentCoversTown(TownID t) const
395 BitmapTileIterator it(this->catchment_tiles);
396 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
397 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) == t) return true;
399 return false;
403 * Recompute tiles covered in our catchment area.
404 * This will additionally recompute nearby towns and industries.
406 void Station::RecomputeCatchment()
408 this->industries_near.clear();
409 this->RemoveFromAllNearbyLists();
411 if (this->rect.IsEmpty()) {
412 this->catchment_tiles.Reset();
413 return;
416 if (!_settings_game.station.serve_neutral_industries && this->industry != nullptr) {
417 /* Station is associated with an industry, so we only need to deliver to that industry. */
418 this->catchment_tiles.Initialize(this->industry->location);
419 for (TileIndex tile : this->industry->location) {
420 if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == this->industry->index) {
421 this->catchment_tiles.SetTile(tile);
424 /* The industry's stations_near may have been computed before its neutral station was built so clear and re-add here. */
425 for (Station *st : this->industry->stations_near) {
426 st->industries_near.erase(this->industry);
428 this->industry->stations_near.clear();
429 this->industry->stations_near.insert(this);
430 this->industries_near.insert(this->industry);
431 return;
434 this->catchment_tiles.Initialize(GetCatchmentRect());
436 /* Loop finding all station tiles */
437 TileArea ta(TileXY(this->rect.left, this->rect.top), TileXY(this->rect.right, this->rect.bottom));
438 for (TileIndex tile : ta) {
439 if (!IsTileType(tile, MP_STATION) || GetStationIndex(tile) != this->index) continue;
441 uint r = GetTileCatchmentRadius(tile, this);
442 if (r == CA_NONE) continue;
444 /* This tile sub-loop doesn't need to test any tiles, they are simply added to the catchment set. */
445 TileArea ta2 = TileArea(tile, 1, 1).Expand(r);
446 for (TileIndex tile2 : ta2) this->catchment_tiles.SetTile(tile2);
449 /* Search catchment tiles for towns and industries */
450 BitmapTileIterator it(this->catchment_tiles);
451 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
452 if (IsTileType(tile, MP_HOUSE)) {
453 Town *t = Town::GetByTile(tile);
454 t->stations_near.insert(this);
456 if (IsTileType(tile, MP_INDUSTRY)) {
457 Industry *i = Industry::GetByTile(tile);
459 /* Ignore industry if it has a neutral station. It already can't be this station. */
460 if (!_settings_game.station.serve_neutral_industries && i->neutral_station != nullptr) continue;
462 i->stations_near.insert(this);
464 /* Add if we can deliver to this industry as well */
465 this->AddIndustryToDeliver(i);
471 * Recomputes catchment of all stations.
472 * This will additionally recompute nearby stations for all towns and industries.
474 /* static */ void Station::RecomputeCatchmentForAll()
476 for (Station *st : Station::Iterate()) { st->RecomputeCatchment(); }
479 /************************************************************************/
480 /* StationRect implementation */
481 /************************************************************************/
483 StationRect::StationRect()
485 this->MakeEmpty();
488 void StationRect::MakeEmpty()
490 this->left = this->top = this->right = this->bottom = 0;
494 * Determines whether a given point (x, y) is within a certain distance of
495 * the station rectangle.
496 * @note x and y are in Tile coordinates
497 * @param x X coordinate
498 * @param y Y coordinate
499 * @param distance The maximum distance a point may have (L1 norm)
500 * @return true if the point is within distance tiles of the station rectangle
502 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
504 return this->left - distance <= x && x <= this->right + distance &&
505 this->top - distance <= y && y <= this->bottom + distance;
508 bool StationRect::IsEmpty() const
510 return this->left == 0 || this->left > this->right || this->top > this->bottom;
513 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
515 int x = TileX(tile);
516 int y = TileY(tile);
517 if (this->IsEmpty()) {
518 /* we are adding the first station tile */
519 if (mode != ADD_TEST) {
520 this->left = this->right = x;
521 this->top = this->bottom = y;
523 } else if (!this->PtInExtendedRect(x, y)) {
524 /* current rect is not empty and new point is outside this rect
525 * make new spread-out rectangle */
526 Rect new_rect = {std::min(x, this->left), std::min(y, this->top), std::max(x, this->right), std::max(y, this->bottom)};
528 /* check new rect dimensions against preset max */
529 int w = new_rect.right - new_rect.left + 1;
530 int h = new_rect.bottom - new_rect.top + 1;
531 if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
532 assert(mode != ADD_TRY);
533 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
536 /* spread-out ok, return true */
537 if (mode != ADD_TEST) {
538 /* we should update the station rect */
539 *this = new_rect;
541 } else {
542 ; // new point is inside the rect, we don't need to do anything
544 return CommandCost();
547 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
549 if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
550 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
551 CommandCost ret = this->BeforeAddTile(tile, mode);
552 if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
553 return ret;
555 return CommandCost();
559 * Check whether station tiles of the given station id exist in the given rectangle
560 * @param st_id Station ID to look for in the rectangle
561 * @param left_a Minimal tile X edge of the rectangle
562 * @param top_a Minimal tile Y edge of the rectangle
563 * @param right_a Maximal tile X edge of the rectangle (inclusive)
564 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
565 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
567 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
569 TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
570 for (TileIndex tile : ta) {
571 if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
574 return false;
577 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
579 int x = TileX(tile);
580 int y = TileY(tile);
582 /* look if removed tile was on the bounding rect edge
583 * and try to reduce the rect by this edge
584 * do it until we have empty rect or nothing to do */
585 for (;;) {
586 /* check if removed tile is on rect edge */
587 bool left_edge = (x == this->left);
588 bool right_edge = (x == this->right);
589 bool top_edge = (y == this->top);
590 bool bottom_edge = (y == this->bottom);
592 /* can we reduce the rect in either direction? */
593 bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
594 bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
595 if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
597 if (reduce_x) {
598 /* reduce horizontally */
599 if (left_edge) {
600 /* move left edge right */
601 this->left = x = x + 1;
602 } else {
603 /* move right edge left */
604 this->right = x = x - 1;
607 if (reduce_y) {
608 /* reduce vertically */
609 if (top_edge) {
610 /* move top edge down */
611 this->top = y = y + 1;
612 } else {
613 /* move bottom edge up */
614 this->bottom = y = y - 1;
618 if (left > right || top > bottom) {
619 /* can't continue, if the remaining rectangle is empty */
620 this->MakeEmpty();
621 return true; // empty remaining rect
624 return false; // non-empty remaining rect
627 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
629 assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
630 assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
632 bool empty = this->AfterRemoveTile(st, ta.tile);
633 if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
634 return empty;
637 StationRect& StationRect::operator = (const Rect &src)
639 this->left = src.left;
640 this->top = src.top;
641 this->right = src.right;
642 this->bottom = src.bottom;
643 return *this;
647 * Calculates the maintenance cost of all airports of a company.
648 * @param owner Company.
649 * @return Total cost.
651 Money AirportMaintenanceCost(Owner owner)
653 Money total_cost = 0;
655 for (const Station *st : Station::Iterate()) {
656 if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
657 total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
660 /* 3 bits fraction for the maintenance cost factor. */
661 return total_cost >> 3;
664 bool StationCompare::operator() (const Station *lhs, const Station *rhs) const
666 return lhs->index < rhs->index;