Codechange: Use null pointer literal instead of the NULL macro
[openttd-github.git] / src / station.cpp
blobb211c6422e9153b4305b6381f3310c36169c1e1f
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file station.cpp Implementation of the station base class. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "company_base.h"
15 #include "roadveh.h"
16 #include "viewport_func.h"
17 #include "viewport_kdtree.h"
18 #include "date_func.h"
19 #include "command_func.h"
20 #include "news_func.h"
21 #include "aircraft.h"
22 #include "vehiclelist.h"
23 #include "core/pool_func.hpp"
24 #include "station_base.h"
25 #include "station_kdtree.h"
26 #include "roadstop_base.h"
27 #include "industry.h"
28 #include "town.h"
29 #include "core/random_func.hpp"
30 #include "linkgraph/linkgraph.h"
31 #include "linkgraph/linkgraphschedule.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)
42 StationKdtree _station_kdtree(Kdtree_StationXYFunc);
44 void RebuildStationKdtree()
46 std::vector<StationID> stids;
47 BaseStation *st;
48 FOR_ALL_STATIONS(st) {
49 stids.push_back(st->index);
51 _station_kdtree.Build(stids.begin(), stids.end());
55 BaseStation::~BaseStation()
57 free(this->name);
58 free(this->speclist);
60 if (CleaningPool()) return;
62 DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->index).Pack());
63 DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->index).Pack());
64 DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->index).Pack());
65 DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->index).Pack());
67 this->sign.MarkDirty();
70 Station::Station(TileIndex tile) :
71 SpecializedStation<Station, false>(tile),
72 bus_station(INVALID_TILE, 0, 0),
73 truck_station(INVALID_TILE, 0, 0),
74 dock_tile(INVALID_TILE),
75 indtype(IT_INVALID),
76 time_since_load(255),
77 time_since_unload(255),
78 last_vehicle_type(VEH_INVALID)
80 /* this->random_bits is set in Station::AddFacility() */
83 /**
84 * Clean up a station by clearing vehicle orders, invalidating windows and
85 * removing link stats.
86 * Aircraft-Hangar orders need special treatment here, as the hangars are
87 * actually part of a station (tiletype is STATION), but the order type
88 * is OT_GOTO_DEPOT.
90 Station::~Station()
92 if (CleaningPool()) {
93 for (CargoID c = 0; c < NUM_CARGO; c++) {
94 this->goods[c].cargo.OnCleanPool();
96 return;
99 while (!this->loading_vehicles.empty()) {
100 this->loading_vehicles.front()->LeaveStation();
103 Aircraft *a;
104 FOR_ALL_AIRCRAFT(a) {
105 if (!a->IsNormalAircraft()) continue;
106 if (a->targetairport == this->index) a->targetairport = INVALID_STATION;
109 for (CargoID c = 0; c < NUM_CARGO; ++c) {
110 LinkGraph *lg = LinkGraph::GetIfValid(this->goods[c].link_graph);
111 if (lg == nullptr) continue;
113 for (NodeID node = 0; node < lg->Size(); ++node) {
114 Station *st = Station::Get((*lg)[node].Station());
115 st->goods[c].flows.erase(this->index);
116 if ((*lg)[node][this->goods[c].node].LastUpdate() != INVALID_DATE) {
117 st->goods[c].flows.DeleteFlows(this->index);
118 RerouteCargo(st, c, this->index, st->index);
121 lg->RemoveNode(this->goods[c].node);
122 if (lg->Size() == 0) {
123 LinkGraphSchedule::instance.Unqueue(lg);
124 delete lg;
128 Vehicle *v;
129 FOR_ALL_VEHICLES(v) {
130 /* Forget about this station if this station is removed */
131 if (v->last_station_visited == this->index) {
132 v->last_station_visited = INVALID_STATION;
134 if (v->last_loading_station == this->index) {
135 v->last_loading_station = INVALID_STATION;
139 /* Remove station from industries and towns that reference it. */
140 this->RemoveFromAllNearbyLists();
142 /* Clear the persistent storage. */
143 delete this->airport.psa;
145 if (this->owner == OWNER_NONE) {
146 /* Invalidate all in case of oil rigs. */
147 InvalidateWindowClassesData(WC_STATION_LIST, 0);
148 } else {
149 InvalidateWindowData(WC_STATION_LIST, this->owner, 0);
152 DeleteWindowById(WC_STATION_VIEW, index);
154 /* Now delete all orders that go to the station */
155 RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index);
157 /* Remove all news items */
158 DeleteStationNews(this->index);
160 for (CargoID c = 0; c < NUM_CARGO; c++) {
161 this->goods[c].cargo.Truncate();
164 CargoPacket::InvalidateAllFrom(this->index);
166 _station_kdtree.Remove(this->index);
167 _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
172 * Invalidating of the JoinStation window has to be done
173 * after removing item from the pool.
174 * @param index index of deleted item
176 void BaseStation::PostDestructor(size_t index)
178 InvalidateWindowData(WC_SELECT_STATION, 0, 0);
182 * Get the primary road stop (the first road stop) that the given vehicle can load/unload.
183 * @param v the vehicle to get the first road stop for
184 * @return the first roadstop that this vehicle can load at
186 RoadStop *Station::GetPrimaryRoadStop(const RoadVehicle *v) const
188 RoadStop *rs = this->GetPrimaryRoadStop(v->IsBus() ? ROADSTOP_BUS : ROADSTOP_TRUCK);
190 for (; rs != nullptr; rs = rs->next) {
191 /* The vehicle cannot go to this roadstop (different roadtype) */
192 if ((GetRoadTypes(rs->xy) & v->compatible_roadtypes) == ROADTYPES_NONE) continue;
193 /* The vehicle is articulated and can therefore not go to a standard road stop. */
194 if (IsStandardRoadStopTile(rs->xy) && v->HasArticulatedPart()) continue;
196 /* The vehicle can actually go to this road stop. So, return it! */
197 break;
200 return rs;
204 * Called when new facility is built on the station. If it is the first facility
205 * it initializes also 'xy' and 'random_bits' members
207 void Station::AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
209 if (this->facilities == FACIL_NONE) {
210 this->MoveSign(facil_xy);
211 this->random_bits = Random();
213 this->facilities |= new_facility_bit;
214 this->owner = _current_company;
215 this->build_date = _date;
219 * Marks the tiles of the station as dirty.
221 * @ingroup dirty
223 void Station::MarkTilesDirty(bool cargo_change) const
225 TileIndex tile = this->train_station.tile;
226 int w, h;
228 if (tile == INVALID_TILE) return;
230 /* cargo_change is set if we're refreshing the tiles due to cargo moving
231 * around. */
232 if (cargo_change) {
233 /* Don't waste time updating if there are no custom station graphics
234 * that might change. Even if there are custom graphics, they might
235 * not change. Unfortunately we have no way of telling. */
236 if (this->num_specs == 0) return;
239 for (h = 0; h < train_station.h; h++) {
240 for (w = 0; w < train_station.w; w++) {
241 if (this->TileBelongsToRailStation(tile)) {
242 MarkTileDirtyByTile(tile);
244 tile += TileDiffXY(1, 0);
246 tile += TileDiffXY(-w, 1);
250 /* virtual */ uint Station::GetPlatformLength(TileIndex tile) const
252 assert(this->TileBelongsToRailStation(tile));
254 TileIndexDiff delta = (GetRailStationAxis(tile) == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
256 TileIndex t = tile;
257 uint len = 0;
258 do {
259 t -= delta;
260 len++;
261 } while (IsCompatibleTrainStationTile(t, tile));
263 t = tile;
264 do {
265 t += delta;
266 len++;
267 } while (IsCompatibleTrainStationTile(t, tile));
269 return len - 1;
272 /* virtual */ uint Station::GetPlatformLength(TileIndex tile, DiagDirection dir) const
274 TileIndex start_tile = tile;
275 uint length = 0;
276 assert(IsRailStationTile(tile));
277 assert(dir < DIAGDIR_END);
279 do {
280 length++;
281 tile += TileOffsByDiagDir(dir);
282 } while (IsCompatibleTrainStationTile(tile, start_tile));
284 return length;
288 * Get the catchment size of an individual station tile.
289 * @param tile Station tile to get catchment size of.
290 * @param st Associated station of station tile.
291 * @pre IsTileType(tile, MP_STATION)
292 * @return The catchment size of the station tile.
294 static uint GetTileCatchmentRadius(TileIndex tile, const Station *st)
296 assert(IsTileType(tile, MP_STATION));
298 if (_settings_game.station.modified_catchment) {
299 switch (GetStationType(tile)) {
300 case STATION_RAIL: return CA_TRAIN;
301 case STATION_OILRIG: return CA_UNMODIFIED;
302 case STATION_AIRPORT: return st->airport.GetSpec()->catchment;
303 case STATION_TRUCK: return CA_TRUCK;
304 case STATION_BUS: return CA_BUS;
305 case STATION_DOCK: return CA_DOCK;
307 default: NOT_REACHED();
308 case STATION_BUOY:
309 case STATION_WAYPOINT: return CA_NONE;
311 } else {
312 switch (GetStationType(tile)) {
313 default: return CA_UNMODIFIED;
314 case STATION_BUOY:
315 case STATION_WAYPOINT: return CA_NONE;
321 * Determines the catchment radius of the station
322 * @return The radius
324 uint Station::GetCatchmentRadius() const
326 uint ret = CA_NONE;
328 if (_settings_game.station.modified_catchment) {
329 if (this->bus_stops != nullptr) ret = max<uint>(ret, CA_BUS);
330 if (this->truck_stops != nullptr) ret = max<uint>(ret, CA_TRUCK);
331 if (this->train_station.tile != INVALID_TILE) ret = max<uint>(ret, CA_TRAIN);
332 if (this->dock_tile != INVALID_TILE) ret = max<uint>(ret, CA_DOCK);
333 if (this->airport.tile != INVALID_TILE) ret = max<uint>(ret, this->airport.GetSpec()->catchment);
334 } else {
335 if (this->bus_stops != nullptr || this->truck_stops != nullptr || this->train_station.tile != INVALID_TILE || this->dock_tile != INVALID_TILE || this->airport.tile != INVALID_TILE) {
336 ret = CA_UNMODIFIED;
340 return ret;
344 * Determines catchment rectangle of this station
345 * @return clamped catchment rectangle
347 Rect Station::GetCatchmentRect() const
349 assert(!this->rect.IsEmpty());
351 /* Compute acceptance rectangle */
352 int catchment_radius = this->GetCatchmentRadius();
354 Rect ret = {
355 max<int>(this->rect.left - catchment_radius, 0),
356 max<int>(this->rect.top - catchment_radius, 0),
357 min<int>(this->rect.right + catchment_radius, MapMaxX()),
358 min<int>(this->rect.bottom + catchment_radius, MapMaxY())
361 return ret;
365 * Add nearby industry to station's industries_near list if it accepts cargo.
366 * @param ind Industry
367 * @param st Station
369 static void AddIndustryToDeliver(Industry *ind, Station *st)
371 /* Don't check further if this industry is already in the list */
372 if (st->industries_near.find(ind) != st->industries_near.end()) return;
374 /* Include only industries that can accept cargo */
375 uint cargo_index;
376 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
377 if (ind->accepts_cargo[cargo_index] != CT_INVALID) break;
379 if (cargo_index >= lengthof(ind->accepts_cargo)) return;
381 st->industries_near.insert(ind);
385 * Remove this station from the nearby stations lists of all towns and industries.
387 void Station::RemoveFromAllNearbyLists()
389 Town *t;
390 FOR_ALL_TOWNS(t) { t->stations_near.erase(this); }
391 Industry *i;
392 FOR_ALL_INDUSTRIES(i) { i->stations_near.erase(this); }
396 * Test if the given town ID is covered by our catchment area.
397 * This is used when removing a house tile to determine if it was the last house tile
398 * within our catchment.
399 * @param t TownID to test.
400 * @return true if at least one house tile of TownID is covered.
402 bool Station::CatchmentCoversTown(TownID t) const
404 BitmapTileIterator it(this->catchment_tiles);
405 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
406 if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) == t) return true;
408 return false;
412 * Recompute tiles covered in our catchment area.
413 * This will additionally recompute nearby towns and industries.
415 void Station::RecomputeCatchment()
417 this->industries_near.clear();
418 this->RemoveFromAllNearbyLists();
420 if (this->rect.IsEmpty()) {
421 this->catchment_tiles.Reset();
422 return;
424 this->catchment_tiles.Initialize(GetCatchmentRect());
426 if (!_settings_game.station.serve_neutral_industries && this->industry != nullptr) {
427 /* Station is associated with an industry, so we only need to deliver to that industry. */
428 TILE_AREA_LOOP(tile, this->industry->location) {
429 if (IsTileType(tile, MP_INDUSTRY) && GetIndustryIndex(tile) == this->industry->index) {
430 this->catchment_tiles.SetTile(tile);
433 /* The industry's stations_near may have been computed before its neutral station was built so clear and re-add here. */
434 for (Station *st : this->industry->stations_near) {
435 st->industries_near.erase(this->industry);
437 this->industry->stations_near.clear();
438 this->industry->stations_near.insert(this);
439 this->industries_near.insert(this->industry);
440 return;
443 /* Loop finding all station tiles */
444 TileArea ta(TileXY(this->rect.left, this->rect.top), TileXY(this->rect.right, this->rect.bottom));
445 TILE_AREA_LOOP(tile, ta) {
446 if (!IsTileType(tile, MP_STATION) || GetStationIndex(tile) != this->index) continue;
448 uint r = GetTileCatchmentRadius(tile, this);
449 if (r == CA_NONE) continue;
451 /* This tile sub-loop doesn't need to test any tiles, they are simply added to the catchment set. */
452 TileArea ta2(TileXY(max<int>(TileX(tile) - r, 0), max<int>(TileY(tile) - r, 0)), TileXY(min<int>(TileX(tile) + r, MapMaxX()), min<int>(TileY(tile) + r, MapMaxY())));
453 TILE_AREA_LOOP(tile2, ta2) this->catchment_tiles.SetTile(tile2);
456 /* Search catchment tiles for towns and industries */
457 BitmapTileIterator it(this->catchment_tiles);
458 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
459 if (IsTileType(tile, MP_HOUSE)) {
460 Town *t = Town::GetByTile(tile);
461 t->stations_near.insert(this);
463 if (IsTileType(tile, MP_INDUSTRY)) {
464 Industry *i = Industry::GetByTile(tile);
466 /* Ignore industry if it has a neutral station. It already can't be this station. */
467 if (!_settings_game.station.serve_neutral_industries && i->neutral_station != nullptr) continue;
469 i->stations_near.insert(this);
471 /* Add if we can deliver to this industry as well */
472 AddIndustryToDeliver(i, this);
478 * Recomputes catchment of all stations.
479 * This will additionally recompute nearby stations for all towns and industries.
481 /* static */ void Station::RecomputeCatchmentForAll()
483 Station *st;
484 FOR_ALL_STATIONS(st) { st->RecomputeCatchment(); }
487 /************************************************************************/
488 /* StationRect implementation */
489 /************************************************************************/
491 StationRect::StationRect()
493 this->MakeEmpty();
496 void StationRect::MakeEmpty()
498 this->left = this->top = this->right = this->bottom = 0;
502 * Determines whether a given point (x, y) is within a certain distance of
503 * the station rectangle.
504 * @note x and y are in Tile coordinates
505 * @param x X coordinate
506 * @param y Y coordinate
507 * @param distance The maximum distance a point may have (L1 norm)
508 * @return true if the point is within distance tiles of the station rectangle
510 bool StationRect::PtInExtendedRect(int x, int y, int distance) const
512 return this->left - distance <= x && x <= this->right + distance &&
513 this->top - distance <= y && y <= this->bottom + distance;
516 bool StationRect::IsEmpty() const
518 return this->left == 0 || this->left > this->right || this->top > this->bottom;
521 CommandCost StationRect::BeforeAddTile(TileIndex tile, StationRectMode mode)
523 int x = TileX(tile);
524 int y = TileY(tile);
525 if (this->IsEmpty()) {
526 /* we are adding the first station tile */
527 if (mode != ADD_TEST) {
528 this->left = this->right = x;
529 this->top = this->bottom = y;
531 } else if (!this->PtInExtendedRect(x, y)) {
532 /* current rect is not empty and new point is outside this rect
533 * make new spread-out rectangle */
534 Rect new_rect = {min(x, this->left), min(y, this->top), max(x, this->right), max(y, this->bottom)};
536 /* check new rect dimensions against preset max */
537 int w = new_rect.right - new_rect.left + 1;
538 int h = new_rect.bottom - new_rect.top + 1;
539 if (mode != ADD_FORCE && (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread)) {
540 assert(mode != ADD_TRY);
541 return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
544 /* spread-out ok, return true */
545 if (mode != ADD_TEST) {
546 /* we should update the station rect */
547 *this = new_rect;
549 } else {
550 ; // new point is inside the rect, we don't need to do anything
552 return CommandCost();
555 CommandCost StationRect::BeforeAddRect(TileIndex tile, int w, int h, StationRectMode mode)
557 if (mode == ADD_FORCE || (w <= _settings_game.station.station_spread && h <= _settings_game.station.station_spread)) {
558 /* Important when the old rect is completely inside the new rect, resp. the old one was empty. */
559 CommandCost ret = this->BeforeAddTile(tile, mode);
560 if (ret.Succeeded()) ret = this->BeforeAddTile(TILE_ADDXY(tile, w - 1, h - 1), mode);
561 return ret;
563 return CommandCost();
567 * Check whether station tiles of the given station id exist in the given rectangle
568 * @param st_id Station ID to look for in the rectangle
569 * @param left_a Minimal tile X edge of the rectangle
570 * @param top_a Minimal tile Y edge of the rectangle
571 * @param right_a Maximal tile X edge of the rectangle (inclusive)
572 * @param bottom_a Maximal tile Y edge of the rectangle (inclusive)
573 * @return \c true if a station tile with the given \a st_id exists in the rectangle, \c false otherwise
575 /* static */ bool StationRect::ScanForStationTiles(StationID st_id, int left_a, int top_a, int right_a, int bottom_a)
577 TileArea ta(TileXY(left_a, top_a), TileXY(right_a, bottom_a));
578 TILE_AREA_LOOP(tile, ta) {
579 if (IsTileType(tile, MP_STATION) && GetStationIndex(tile) == st_id) return true;
582 return false;
585 bool StationRect::AfterRemoveTile(BaseStation *st, TileIndex tile)
587 int x = TileX(tile);
588 int y = TileY(tile);
590 /* look if removed tile was on the bounding rect edge
591 * and try to reduce the rect by this edge
592 * do it until we have empty rect or nothing to do */
593 for (;;) {
594 /* check if removed tile is on rect edge */
595 bool left_edge = (x == this->left);
596 bool right_edge = (x == this->right);
597 bool top_edge = (y == this->top);
598 bool bottom_edge = (y == this->bottom);
600 /* can we reduce the rect in either direction? */
601 bool reduce_x = ((left_edge || right_edge) && !ScanForStationTiles(st->index, x, this->top, x, this->bottom));
602 bool reduce_y = ((top_edge || bottom_edge) && !ScanForStationTiles(st->index, this->left, y, this->right, y));
603 if (!(reduce_x || reduce_y)) break; // nothing to do (can't reduce)
605 if (reduce_x) {
606 /* reduce horizontally */
607 if (left_edge) {
608 /* move left edge right */
609 this->left = x = x + 1;
610 } else {
611 /* move right edge left */
612 this->right = x = x - 1;
615 if (reduce_y) {
616 /* reduce vertically */
617 if (top_edge) {
618 /* move top edge down */
619 this->top = y = y + 1;
620 } else {
621 /* move bottom edge up */
622 this->bottom = y = y - 1;
626 if (left > right || top > bottom) {
627 /* can't continue, if the remaining rectangle is empty */
628 this->MakeEmpty();
629 return true; // empty remaining rect
632 return false; // non-empty remaining rect
635 bool StationRect::AfterRemoveRect(BaseStation *st, TileArea ta)
637 assert(this->PtInExtendedRect(TileX(ta.tile), TileY(ta.tile)));
638 assert(this->PtInExtendedRect(TileX(ta.tile) + ta.w - 1, TileY(ta.tile) + ta.h - 1));
640 bool empty = this->AfterRemoveTile(st, ta.tile);
641 if (ta.w != 1 || ta.h != 1) empty = empty || this->AfterRemoveTile(st, TILE_ADDXY(ta.tile, ta.w - 1, ta.h - 1));
642 return empty;
645 StationRect& StationRect::operator = (const Rect &src)
647 this->left = src.left;
648 this->top = src.top;
649 this->right = src.right;
650 this->bottom = src.bottom;
651 return *this;
655 * Calculates the maintenance cost of all airports of a company.
656 * @param owner Company.
657 * @return Total cost.
659 Money AirportMaintenanceCost(Owner owner)
661 Money total_cost = 0;
663 const Station *st;
664 FOR_ALL_STATIONS(st) {
665 if (st->owner == owner && (st->facilities & FACIL_AIRPORT)) {
666 total_cost += _price[PR_INFRASTRUCTURE_AIRPORT] * st->airport.GetSpec()->maintenance_cost;
669 /* 3 bits fraction for the maintenance cost factor. */
670 return total_cost >> 3;
673 bool StationCompare::operator() (const Station *lhs, const Station *rhs) const
675 return lhs->index < rhs->index;