OpenTTD Source 20261112-master-gbcbec5e63f
station_cmd.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "core/flatset_type.hpp"
12#include "aircraft.h"
13#include "bridge.h"
14#include "bridge_map.h"
15#include "tilearea_spiral.h"
16#include "vehiclelist_func.h"
17#include "viewport_func.h"
18#include "viewport_kdtree.h"
19#include "command_func.h"
20#include "town.h"
21#include "news_func.h"
22#include "train.h"
23#include "ship.h"
24#include "roadveh.h"
25#include "industry.h"
26#include "newgrf_cargo.h"
27#include "newgrf_debug.h"
28#include "newgrf_station.h"
29#include "newgrf_canal.h" /* For the buoy */
31#include "road_internal.h" /* For drawing catenary/checking road removal */
32#include "autoslope.h"
33#include "water.h"
34#include "tilehighlight_func.h"
35#include "strings_func.h"
36#include "clear_func.h"
38#include "vehicle_func.h"
39#include "string_func.h"
40#include "animated_tile_func.h"
41#include "elrail_func.h"
42#include "station_base.h"
43#include "station_func.h"
44#include "station_kdtree.h"
45#include "roadstop_base.h"
46#include "newgrf_railtype.h"
47#include "newgrf_roadtype.h"
48#include "waypoint_base.h"
49#include "waypoint_func.h"
50#include "pbs.h"
51#include "debug.h"
52#include "core/random_func.hpp"
54#include "company_base.h"
56#include "newgrf_airporttiles.h"
57#include "order_backup.h"
58#include "newgrf_house.h"
59#include "company_gui.h"
61#include "linkgraph/refresh.h"
62#include "station_cmd.h"
63#include "waypoint_cmd.h"
64#include "landscape_cmd.h"
65#include "rail_cmd.h"
66#include "newgrf_roadstop.h"
67#include "timer/timer.h"
71#include "cheat_type.h"
72#include "road_func.h"
73#include "station_layout_type.h"
74#include "tilearea_airport.h"
76
78
79#include "table/strings.h"
80#include "table/station_land.h"
81
82#include <bitset>
83
84#include "safeguards.h"
85
91/* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
92
100{
101 assert(IsTileType(t, TileType::Station));
102
103 /* If the tile isn't an airport there's no chance it's a hangar. */
104 if (!IsAirport(t)) return false;
105
106 const Station *st = Station::GetByTile(t);
107 const AirportSpec *as = st->airport.GetSpec();
108
109 for (const auto &depot : as->depots) {
110 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
111 }
112
113 return false;
114}
115
125template <class T, class F>
126CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
127{
128 ta.Expand(1);
129
130 /* check around to see if there are any stations there owned by the company */
131 for (TileIndex tile_cur : ta) {
132 if (IsTileType(tile_cur, TileType::Station)) {
133 StationID t = GetStationIndex(tile_cur);
134 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
135 if (closest_station == StationID::Invalid()) {
136 closest_station = t;
137 } else if (closest_station != t) {
138 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
139 }
140 }
141 }
142 *st = (closest_station == StationID::Invalid()) ? nullptr : T::Get(closest_station);
143 return CommandCost();
144}
145
151typedef bool (*CMSAMatcher)(TileIndex tile);
152
160{
161 int num = 0;
162
163 for (int dx = -3; dx <= 3; dx++) {
164 for (int dy = -3; dy <= 3; dy++) {
165 TileIndex t = TileAddWrap(tile, dx, dy);
166 if (t != INVALID_TILE && cmp(t)) num++;
167 }
168 }
169
170 return num;
171}
172
178static bool CMSAMine(TileIndex tile)
179{
180 /* No industry */
181 if (!IsTileType(tile, TileType::Industry)) return false;
182
183 const Industry *ind = Industry::GetByTile(tile);
184
185 /* No extractive industry */
187
188 for (const auto &p : ind->produced) {
189 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
190 * Also the production of passengers and mail is ignored. */
191 if (IsValidCargoType(p.cargo) &&
192 !CargoSpec::Get(p.cargo)->classes.Any({CargoClass::Liquid, CargoClass::Passengers, CargoClass::Mail})) {
193 return true;
194 }
195 }
196
197 return false;
198}
199
205static bool CMSAWater(TileIndex tile)
206{
207 return IsTileType(tile, TileType::Water) && IsWater(tile);
208}
209
215static bool CMSATree(TileIndex tile)
216{
217 return IsTileType(tile, TileType::Trees);
218}
219
229
232 std::bitset<(STR_SV_STNAME_FALLBACK - STR_SV_STNAME).base()> used_names;
233 std::bitset<NUM_INDUSTRYTYPES> indtypes;
234
240 bool IsAvailable(StringID str) const
241 {
242 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
243 return !this->used_names.test((str - STR_SV_STNAME).base());
244 }
245
251 {
252 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
253 this->used_names.set((str - STR_SV_STNAME).base());
254 }
255};
256
266{
267 const Town *t = st->town;
268
270
271 for (const Station *s : Station::Iterate()) {
272 if (s != st && s->town == t) {
273 if (s->indtype != IT_INVALID) {
274 sni.indtypes[s->indtype] = true;
275 StringID name = GetIndustrySpec(s->indtype)->station_name;
276 if (name != STR_UNDEFINED) {
277 /* Filter for other industrytypes with the same name */
278 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
279 const IndustrySpec *indsp = GetIndustrySpec(it);
280 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
281 }
282 }
283 continue;
284 }
285 if (IsInsideMM(s->string_id, STR_SV_STNAME, STR_SV_STNAME_FALLBACK)) {
286 auto str = s->string_id;
287 if (str == STR_SV_STNAME_FOREST) str = STR_SV_STNAME_WOODS;
288 sni.SetUsed(str);
289 }
290 }
291 }
292
293 for (auto indtile : SpiralTileSequence(tile, 7)) {
294 if (!IsTileType(indtile, TileType::Industry)) continue;
295
296 /* If the station name is undefined it means that it doesn't name a station */
297 IndustryType indtype = GetIndustryType(indtile);
298 const IndustrySpec *indsp = GetIndustrySpec(indtype);
299 if (indsp->station_name == STR_UNDEFINED) continue;
300
301 /* In all cases if an industry that provides a name is found two of
302 * the standard names will be disabled. */
303 sni.SetUsed(STR_SV_STNAME_OILFIELD);
304 sni.SetUsed(STR_SV_STNAME_MINES);
305 if (sni.indtypes[indtype]) continue;
306
307 /* STR_NULL means it only disables oil rig/mines */
308 if (indsp->station_name != STR_NULL) {
309 st->indtype = indtype;
310 return STR_SV_STNAME_FALLBACK;
311 }
312 break;
313 }
314
315 /* check default names
316 * Oil rigs/mines name could be marked not free by looking for a near by industry. */
317 switch (name_class) {
319 if (sni.IsAvailable(STR_SV_STNAME_AIRPORT)) return STR_SV_STNAME_AIRPORT;
320 break;
322 if (sni.IsAvailable(STR_SV_STNAME_OILFIELD)) return STR_SV_STNAME_OILFIELD;
323 break;
325 if (sni.IsAvailable(STR_SV_STNAME_DOCKS)) return STR_SV_STNAME_DOCKS;
326 break;
328 if (sni.IsAvailable(STR_SV_STNAME_HELIPORT)) return STR_SV_STNAME_HELIPORT;
329 break;
330 default:
331 break;
332 };
333
334 /* check mine? */
335 if (sni.IsAvailable(STR_SV_STNAME_MINES)) {
336 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
337 return STR_SV_STNAME_MINES;
338 }
339 }
340
341 /* check close enough to town to get central as name? */
342 if (DistanceMax(tile, t->xy) < 8) {
343 if (sni.IsAvailable(STR_SV_STNAME)) return STR_SV_STNAME;
344 if (sni.IsAvailable(STR_SV_STNAME_CENTRAL)) return STR_SV_STNAME_CENTRAL;
345 }
346
347 /* Check lakeside */
348 if (sni.IsAvailable(STR_SV_STNAME_LAKESIDE) &&
349 DistanceFromEdge(tile) < 20 &&
350 CountMapSquareAround(tile, CMSAWater) >= 5) {
351 return STR_SV_STNAME_LAKESIDE;
352 }
353
354 /* Check woods */
355 if (sni.IsAvailable(STR_SV_STNAME_WOODS) && (
356 CountMapSquareAround(tile, CMSATree) >= 8 ||
358 ) {
359 return _settings_game.game_creation.landscape == LandscapeType::Tropic ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
360 }
361
362 /* check elevation compared to town */
363 int z = GetTileZ(tile);
364 int z2 = GetTileZ(t->xy);
365 if (z < z2) {
366 if (sni.IsAvailable(STR_SV_STNAME_VALLEY)) return STR_SV_STNAME_VALLEY;
367 } else if (z > z2) {
368 if (sni.IsAvailable(STR_SV_STNAME_HEIGHTS)) return STR_SV_STNAME_HEIGHTS;
369 }
370
371 /* check direction compared to town */
372 if (TileX(tile) < TileX(t->xy)) {
373 sni.SetUsed(STR_SV_STNAME_SOUTH);
374 sni.SetUsed(STR_SV_STNAME_WEST);
375 } else {
376 sni.SetUsed(STR_SV_STNAME_NORTH);
377 sni.SetUsed(STR_SV_STNAME_EAST);
378 }
379 if (TileY(tile) < TileY(t->xy)) {
380 sni.SetUsed(STR_SV_STNAME_SOUTH);
381 sni.SetUsed(STR_SV_STNAME_EAST);
382 } else {
383 sni.SetUsed(STR_SV_STNAME_NORTH);
384 sni.SetUsed(STR_SV_STNAME_WEST);
385 }
386
388 static const StringID fallback_names[] = {
389 STR_SV_STNAME_NORTH,
390 STR_SV_STNAME_SOUTH,
391 STR_SV_STNAME_EAST,
392 STR_SV_STNAME_WEST,
393 STR_SV_STNAME_TRANSFER,
394 STR_SV_STNAME_HALT,
395 STR_SV_STNAME_EXCHANGE,
396 STR_SV_STNAME_ANNEXE,
397 STR_SV_STNAME_SIDINGS,
398 STR_SV_STNAME_BRANCH,
399 STR_SV_STNAME_UPPER,
400 STR_SV_STNAME_LOWER,
401 };
402 for (auto str : fallback_names) {
403 if (sni.IsAvailable(str)) return str;
404 }
405 return STR_SV_STNAME_FALLBACK;
406}
407
414{
415 uint threshold = 8;
416
417 Station *best_station = nullptr;
418 ForAllStationsRadius(tile, threshold, [&](Station *st) {
419 if (!st->IsInUse() && st->owner == _current_company) {
420 uint cur_dist = DistanceManhattan(tile, st->xy);
421
422 if (cur_dist < threshold) {
423 threshold = cur_dist;
424 best_station = st;
425 } else if (cur_dist == threshold && best_station != nullptr) {
426 /* In case of a tie, lowest station ID wins */
427 if (st->index < best_station->index) best_station = st;
428 }
429 }
430 });
431
432 return best_station;
433}
434
435
437{
438 switch (type) {
439 case StationType::Rail: return this->train_station;
440 case StationType::Airport: return this->airport;
441 case StationType::Truck: return this->truck_station;
442 case StationType::Bus: return this->bus_station;
444 case StationType::Oilrig: return this->docking_station;
445 default: NOT_REACHED();
446 }
447}
448
453{
454 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
455
456 pt.y -= 32 * ZOOM_BASE;
457 if (this->facilities.Test(StationFacility::Airport) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
458
459 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
460
461 this->sign.UpdatePosition(pt.x, pt.y, GetString(STR_VIEWPORT_STATION, this->index, this->facilities), GetString(STR_STATION_NAME, this->index, this->facilities));
462
463 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
464
465 SetWindowDirty(WindowClass::StationView, this->index);
466}
467
473{
474 if (this->xy == new_xy) return;
475
476 _station_kdtree.Remove(this->index);
477
478 this->BaseStation::MoveSign(new_xy);
479
480 _station_kdtree.Insert(this->index);
481}
482
485{
486 for (BaseStation *st : BaseStation::Iterate()) {
487 st->UpdateVirtCoord();
488 }
489}
490
491void BaseStation::FillCachedName() const
492{
493 auto tmp_params = MakeParameters(this->index);
494 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
495}
496
497void ClearAllStationCachedNames()
498{
499 for (BaseStation *st : BaseStation::Iterate()) {
500 st->cached_name.clear();
501 }
502}
503
510{
511 CargoTypes mask{};
512
513 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
514 if (it->status.Test(GoodsEntry::State::Acceptance)) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
515 }
516 return mask;
517}
518
525{
526 CargoTypes mask{};
527
528 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
529 if (it->TotalCount() > 0) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
530 }
531 return mask;
532}
533
540static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
541{
542 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
544}
545
554CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
555{
556 CargoArray produced{};
557 FlatSet<IndustryID> industries;
558 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
559
560 /* Loop over all tiles to get the produced cargo of
561 * everything except industries */
562 for (TileIndex tile : ta) {
563 if (IsTileType(tile, TileType::Industry)) industries.insert(GetIndustryIndex(tile));
564 AddProducedCargo(tile, produced);
565 }
566
567 /* Loop over the seen industries. They produce cargo for
568 * anything that is within 'rad' of any one of their tiles.
569 */
570 for (IndustryID industry : industries) {
571 const Industry *i = Industry::Get(industry);
572 /* Skip industry with neutral station */
573 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
574
575 for (const auto &p : i->produced) {
576 if (IsValidCargoType(p.cargo)) produced[p.cargo]++;
577 }
578 }
579
580 return produced;
581}
582
591std::pair<CargoArray, CargoTypes> GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
592{
593 CargoArray acceptance{};
594 CargoTypes always_accepted{};
595
596 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
597
598 for (TileIndex tile : ta) {
599 /* Ignore industry if it has a neutral station. */
600 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, TileType::Industry) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
601
602 AddAcceptedCargo(tile, acceptance, always_accepted);
603 }
604
605 return {acceptance, always_accepted};
606}
607
613static std::pair<CargoArray, CargoTypes> GetAcceptanceAroundStation(const Station *st)
614{
615 CargoArray acceptance{};
616 CargoTypes always_accepted{};
617
618 for (TileIndex tile : st->catchment_tiles) {
619 AddAcceptedCargo(tile, acceptance, always_accepted);
620 }
621
622 return {acceptance, always_accepted};
623}
624
630void UpdateStationAcceptance(Station *st, bool show_msg)
631{
632 /* old accepted goods types */
633 CargoTypes old_acc = GetAcceptanceMask(st);
634
635 /* And retrieve the acceptance. */
636 CargoArray acceptance{};
637 if (!st->spread.IsEmpty()) {
638 std::tie(acceptance, st->always_accepted) = GetAcceptanceAroundStation(st);
639 }
640
641 /* Adjust in case our station only accepts fewer kinds of goods */
642 for (CargoType cargo : EnumRange(NUM_CARGO)) {
643 uint amt = acceptance[cargo];
644
645 /* Make sure the station can accept the goods type. */
646 bool is_passengers = IsCargoInClass(cargo, CargoClass::Passengers);
647 if ((!is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::TruckStop, StationFacility::Airport, StationFacility::Dock})) ||
648 (is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::BusStop, StationFacility::Airport, StationFacility::Dock}))) {
649 amt = 0;
650 }
651
652 GoodsEntry &ge = st->goods[cargo];
655 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
656 }
657 }
658
659 /* Only show a message in case the acceptance was actually changed. */
660 CargoTypes new_acc = GetAcceptanceMask(st);
661 if (old_acc == new_acc) return;
662
663 /* show a message to report that the acceptance was changed? */
664 if (show_msg && st->owner == _local_company && st->IsInUse()) {
665 /* Combine old and new masks to get changes */
666 CargoTypes accepts = new_acc & CargoTypes{old_acc}.Flip();
667 CargoTypes rejects = CargoTypes{new_acc}.Flip() & old_acc;
668
669 /* Show news message if there are any changes */
670 if (accepts.Any()) ShowRejectOrAcceptNews(st, accepts, false);
671 if (rejects.Any()) ShowRejectOrAcceptNews(st, rejects, true);
672 }
673
674 /* redraw the station view since acceptance changed */
675 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_ACCEPT_RATING_LIST);
676}
677
678static void UpdateStationSignCoord(BaseStation *st)
679{
680 if (st->spread.IsEmpty()) return; // no tiles belong to this station
681
682 /* clamp sign coord to be inside the station rect */
683 if (!st->spread.Contains(st->xy)) {
684 int left = TileX(st->spread.tile);
685 int right = left + st->spread.w - 1;
686 int top = TileY(st->spread.tile);
687 int bottom = top + st->spread.h - 1;
688
689 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), left, right), ClampU(TileY(st->xy), top, bottom));
690 st->MoveSign(new_xy);
691 }
692
693 if (!Station::IsExpected(st)) return;
694 Station *full_station = Station::From(st);
695 for (const GoodsEntry &ge : full_station->goods) {
696 LinkGraphID lg = ge.link_graph;
697 if (!LinkGraph::IsValidID(lg)) continue;
698 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
699 }
700}
701
711static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reuse, TileArea area, StationNaming name_class)
712{
713 /* Find a deleted station close to us */
714 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
715
716 if (*st != nullptr) {
717 if ((*st)->owner != _current_company) {
718 return CommandCost(CMD_ERROR);
719 }
720
721 CommandCost ret = CheckStationSpread((*st)->spread, area);
722 if (ret.Failed()) return ret;
723 } else {
724 /* allocate and initialize new station */
725 if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
726
727 if (flags.Test(DoCommandFlag::Execute)) {
728 *st = Station::Create(area.tile);
729 _station_kdtree.Insert((*st)->index);
730
731 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
732 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
733
735 (*st)->town->have_ratings.Set(_current_company);
736 }
737 }
738 }
739 return CommandCost();
740}
741
749{
750 if (!st->IsInUse()) {
751 st->delete_ctr = 0;
752 InvalidateWindowData(WindowClass::StationList, st->owner, 0);
753 }
754 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
755 UpdateStationSignCoord(st);
756}
757
764{
765 this->UpdateVirtCoord();
767
768 if (adding) {
769 this->RecomputeCatchment();
770 MarkCatchmentTilesDirty();
771 InvalidateWindowData(WindowClass::StationList, this->owner, 0);
772 } else {
773 MarkCatchmentTilesDirty();
774 }
775
776 switch (type) {
778 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_TRAINS);
779 break;
781 break;
783 case StationType::Bus:
784 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_ROADVEHS);
785 break;
787 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_SHIPS);
788 break;
789 default: NOT_REACHED();
790 }
791
792 if (adding) {
793 UpdateStationAcceptance(this, false);
794 InvalidateWindowData(WindowClass::JoinStation, 0, 0);
795 } else {
797 this->RecomputeCatchment();
798 }
799
800}
801
803
813CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
814{
815 if (check_bridge && IsBridgeAbove(tile)) {
816 return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
817 }
818
820 if (ret.Failed()) return ret;
821
822 auto [tileh, z] = GetTileSlopeZ(tile);
823
824 /* Prohibit building if
825 * 1) The tile is "steep" (i.e. stretches two height levels).
826 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
827 */
828 if ((!allow_steep && IsSteepSlope(tileh)) ||
829 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
830 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
831 }
832
834 int flat_z = z + GetSlopeMaxZ(tileh);
835 if (tileh != SLOPE_FLAT) {
836 /* Forbid building if the tile faces a slope in a invalid direction. */
838 if (invalid_dirs.Test(dir) && !CanBuildDepotByTileh(dir, tileh)) {
839 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
840 }
841 }
843 }
844
845 /* The level of this tile must be equal to allowed_z. */
846 if (allowed_z < 0) {
847 /* First tile. */
848 allowed_z = flat_z;
849 } else if (allowed_z != flat_z) {
850 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
851 }
852
853 return cost;
854}
855
863{
865 int allowed_z = -1;
866
867 for (; *tile_iter != INVALID_TILE; ++tile_iter) {
869 if (!IsTileType(*tile_iter, TileType::Clear) || !IsTileFlat(*tile_iter)) {
870 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
871 }
872 } else {
873 CommandCost ret = CheckBuildableTile(*tile_iter, {}, allowed_z, true);
874 if (ret.Failed()) return ret;
875 cost.AddCost(ret.GetCost());
876
877 ret = Command<Commands::LandscapeClear>::Do(flags, *tile_iter);
878 if (ret.Failed()) return ret;
879 cost.AddCost(ret.GetCost());
880 }
881 }
882
883 return cost;
884}
885
892{
894 STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION, // Rail
895 INVALID_STRING_ID, // Airport
896 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Truck
897 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Bus
898 INVALID_STRING_ID, // Oilrig
899 STR_ERROR_BRIDGE_TOO_LOW_FOR_DOCK, // Dock
900 STR_ERROR_BRIDGE_TOO_LOW_FOR_BUOY, // Buoy
901 STR_ERROR_BRIDGE_TOO_LOW_FOR_RAIL_WAYPOINT, // RailWaypoint
902 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROAD_WAYPOINT, // RoadWaypoint
903 };
904 return too_low_msgs[type];
905};
906
917static CommandCost IsStationBridgeAboveOk(TileIndex tile, std::span<const BridgeableTileInfo> bridgeable_info, StationType type, StationGfx layout, int bridge_height, StringID disallowed_msg = INVALID_STRING_ID)
918{
919 int height = layout < std::size(bridgeable_info) ? bridgeable_info[layout].height : 0;
920
921 if (height == 0) {
922 if (disallowed_msg != INVALID_STRING_ID) return CommandCost{disallowed_msg};
923 /* Get normal error message associated with clearing the tile. */
924 return Command<Commands::LandscapeClear>::Do(DoCommandFlag::Auto, tile);
925 }
926
927 int height_diff = GetTileMaxZ(tile) + height - bridge_height;
928 if (height_diff > 0) return CommandCostWithParam(GetBridgeTooLowMessageForStationType(type), height_diff * TILE_HEIGHT_STEP);
929 return CommandCost{};
930}
931
937static std::span<const BridgeableTileInfo> GetStationBridgeableTileInfo(StationType type)
938{
939 return _station_bridgeable_info[type];
940}
941
951{
952 if (!IsBridgeAbove(tile)) return CommandCost();
953
954 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
955 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
956 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
957}
958
968{
969 if (!IsBridgeAbove(tile)) return CommandCost();
970
971 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
972 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
973 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
974}
975
983{
984 if (!IsBridgeAbove(tile)) return CommandCost();
985
986 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
987 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Dock);
988 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Dock, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
989}
990
997{
998 if (!IsBridgeAbove(tile)) return CommandCost();
999
1000 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
1001 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Buoy);
1002 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Buoy, 0, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
1003}
1004
1021static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlags flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
1022{
1024 DiagDirections invalid_dirs = AxisToDiagDirs(axis);
1025
1026 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1027 bool slope_cb = statspec != nullptr && statspec->callback_mask.Test(StationCallbackMask::SlopeCheck);
1028
1029 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false, false);
1030 if (ret.Failed()) return ret;
1031 cost.AddCost(ret.GetCost());
1032
1033 if (slope_cb) {
1034 /* Do slope check if requested. */
1035 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
1036 if (ret.Failed()) return ret;
1037 }
1038
1039 /* if station is set, then we have special handling to allow building on top of already existing stations.
1040 * so station points to StationID::Invalid() if we can build on any station.
1041 * Or it points to a station if we're only allowed to build on exactly that station. */
1042 if (station != nullptr && IsTileType(tile_cur, TileType::Station)) {
1043 if (!IsRailStation(tile_cur)) {
1044 return ClearTile_Station(tile_cur, DoCommandFlag::Auto); // get error message
1045 } else {
1046 StationID st = GetStationIndex(tile_cur);
1047 if (*station == StationID::Invalid()) {
1048 *station = st;
1049 } else if (*station != st) {
1050 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1051 }
1052 }
1053 } else {
1054 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
1055 if (rt != INVALID_RAILTYPE && IsPlainRailTile(tile_cur)) {
1056 /* Don't overbuild signals. */
1057 if (HasSignals(tile_cur)) return CommandCost(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
1058
1059 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
1060 if (HasPowerOnRail(GetRailType(tile_cur), rt)) {
1061 /* The existing track must align with the desired station axis. */
1062 Track track = AxisToTrack(axis);
1063 if (GetTrackBits(tile_cur) == track) {
1064 /* Check for trains having a reservation for this tile. */
1065 if (GetRailReservationTrackBits(tile_cur).Test(track)) {
1066 Train *v = GetTrainForReservation(tile_cur, track);
1067 if (v != nullptr) {
1068 affected_vehicles.push_back(v);
1069 }
1070 }
1071 ret = Command<Commands::RemoveRail>::Do(flags, tile_cur, track);
1072 if (ret.Failed()) return ret;
1073 cost.AddCost(ret.GetCost());
1074 /* With DoCommandFlags{flags}.Reset(DoCommandFlag::Execute) CmdLandscapeClear would fail since the rail still exists */
1075 return cost;
1076 }
1077 }
1078 }
1079 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
1080 if (ret.Failed()) return ret;
1081 cost.AddCost(ret.GetCost());
1082 }
1083
1084 return cost;
1085}
1086
1101static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, const RoadStopSpec *spec, DoCommandFlags flags, DiagDirections invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
1102{
1104
1105 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through, false);
1106 if (ret.Failed()) return ret;
1107 cost.AddCost(ret.GetCost());
1108
1109 ret = IsRoadStationBridgeAboveOk(cur_tile, spec, station_type, is_drive_through ? GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET + to_underlying(axis) : FindFirstBit(invalid_dirs.base()));
1110 if (ret.Failed()) return ret;
1111
1112 /* If station is set, then we have special handling to allow building on top of already existing stations.
1113 * Station points to StationID::Invalid() if we can build on any station.
1114 * Or it points to a station if we're only allowed to build on exactly that station. */
1115 if (station != nullptr && IsTileType(cur_tile, TileType::Station)) {
1116 if (!IsAnyRoadStop(cur_tile)) {
1117 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1118 } else {
1119 if (station_type != GetStationType(cur_tile) ||
1120 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
1121 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1122 }
1123 /* Drive-through station in the wrong direction. */
1124 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
1125 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1126 }
1127 StationID st = GetStationIndex(cur_tile);
1128 if (*station == StationID::Invalid()) {
1129 *station = st;
1130 } else if (*station != st) {
1131 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1132 }
1133 }
1134 } else {
1135 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1136 /* Road bits in the wrong direction. */
1137 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : RoadBits{};
1138 if (build_over_road && rb.Any(AxisToRoadBits(OtherAxis(axis)))) {
1139 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1140 switch (rb.Count()) {
1141 case 1:
1142 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1143
1144 case 2:
1145 if (rb == ROAD_X || rb == ROAD_Y) return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1146 return CommandCost(STR_ERROR_DRIVE_THROUGH_CORNER);
1147
1148 default: // 3 or 4
1149 return CommandCost(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1150 }
1151 }
1152
1153 if (build_over_road) {
1154 /* There is a road, check if we can build road+tram stop over it. */
1155 RoadType road_rt = GetRoadType(cur_tile, RoadTramType::Road);
1156 if (road_rt != INVALID_ROADTYPE) {
1157 Owner road_owner = GetRoadOwner(cur_tile, RoadTramType::Road);
1158 if (road_owner == OWNER_TOWN) {
1159 if (!_settings_game.construction.road_stop_on_town_road) return CommandCost(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1160 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1161 ret = CheckOwnership(road_owner);
1162 if (ret.Failed()) return ret;
1163 }
1164 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Road).Count();
1165
1166 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1167
1168 if (GetDisallowedRoadDirections(cur_tile).Any() && road_owner != OWNER_TOWN && road_owner != OWNER_NONE) {
1169 ret = CheckOwnership(road_owner);
1170 if (ret.Failed()) return ret;
1171 }
1172
1173 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1174 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1175 cost.AddCost(RoadBuildCost(rt) * 2);
1176 }
1177
1178 /* There is a tram, check if we can build road+tram stop over it. */
1179 RoadType tram_rt = GetRoadType(cur_tile, RoadTramType::Tram);
1180 if (tram_rt != INVALID_ROADTYPE) {
1181 Owner tram_owner = GetRoadOwner(cur_tile, RoadTramType::Tram);
1182 if (Company::IsValidID(tram_owner) &&
1183 (!_settings_game.construction.road_stop_on_competitor_road ||
1184 /* Disallow breaking end-of-line of someone else
1185 * so trams can still reverse on this tile. */
1186 GetRoadBits(cur_tile, RoadTramType::Tram).Count() == 1)) {
1187 ret = CheckOwnership(tram_owner);
1188 if (ret.Failed()) return ret;
1189 }
1190 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Tram).Count();
1191
1192 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1193
1194 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1195 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1196 cost.AddCost(RoadBuildCost(rt) * 2);
1197 }
1198 } else if (rt == INVALID_ROADTYPE) {
1199 return CommandCost(STR_ERROR_THERE_IS_NO_ROAD);
1200 } else {
1201 ret = Command<Commands::LandscapeClear>::Do(flags, cur_tile);
1202 if (ret.Failed()) return ret;
1203 cost.AddCost(ret.GetCost());
1204 cost.AddCost(RoadBuildCost(rt) * 2);
1205 }
1206 }
1207
1208 return cost;
1209}
1210
1212template <>
1214{
1215 /* Use predefined layout if it exists. Mask bit zero which will indicate axis. */
1216 if (!stl.layout.empty()) return this->stl.layout[this->position] & ~1;
1217
1218 if (this->stl.length == 1) {
1219 /* Special case for 1-long platforms, all bare platforms except one small building. */
1220 return this->position == ((this->stl.platforms - 1) / 2) ? 2 : 0;
1221 }
1222
1223 if ((this->position < this->stl.length && (this->stl.platforms % 2 == 1))) {
1224 /* Number of tracks is odd, make the first platform bare with a small building. */
1225 return this->position == ((this->stl.length - 1) / 2) ? 2 : 0;
1226 }
1227
1228 if (this->stl.length > 4 && ((this->position % this->stl.length) == 0 || (this->position % this->stl.length) == this->stl.length - 1)) {
1229 /* Station is longer than 4 tiles, place bare platforms at either end. */
1230 return 0;
1231 }
1232
1233 /* None of the above so must be north or south part of larger station. */
1234 return (((this->position / this->stl.length) % 2) == (this->stl.platforms % 2)) ? 4 : 6;
1235}
1236
1250template <class T, class F>
1251CommandCost FindJoiningBaseStation(StringID error_message, StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1252{
1253 assert(*st == nullptr);
1254 bool check_surrounding = true;
1255
1256 if (existing_station != StationID::Invalid()) {
1257 if (adjacent && existing_station != station_to_join) {
1258 /* You can't build an adjacent station over the top of one that
1259 * already exists. */
1260 return CommandCost(error_message);
1261 } else {
1262 /* Extend the current station, and don't check whether it will
1263 * be near any other stations. */
1264 T *candidate = T::GetIfValid(existing_station);
1265 if (candidate != nullptr && filter(candidate)) *st = candidate;
1266 check_surrounding = (*st == nullptr);
1267 }
1268 } else {
1269 /* There's no station here. Don't check the tiles surrounding this
1270 * one if the company wanted to build an adjacent station. */
1271 if (adjacent) check_surrounding = false;
1272 }
1273
1274 if (check_surrounding) {
1275 /* Make sure there is no more than one other station around us that is owned by us. */
1276 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1277 if (ret.Failed()) return ret;
1278 }
1279
1280 /* Distant join */
1281 if (*st == nullptr && station_to_join != StationID::Invalid()) *st = T::GetIfValid(station_to_join);
1282
1283 return CommandCost();
1284}
1285
1295static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1296{
1297 return FindJoiningBaseStation<Station>(STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST, existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1298}
1299
1310CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1311{
1312 if (is_road) {
1313 return FindJoiningBaseStation<Waypoint>(STR_ERROR_MUST_REMOVE_ROADWAYPOINT_FIRST, existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return HasBit(wp->waypoint_flags, WPF_ROAD); });
1314 } else {
1315 return FindJoiningBaseStation<Waypoint>(STR_ERROR_MUST_REMOVE_RAILWAYPOINT_FIRST, existing_waypoint, waypoint_to_join, adjacent, ta, wp, [](const Waypoint *wp) -> bool { return !HasBit(wp->waypoint_flags, WPF_ROAD); });
1316 }
1317}
1318
1330
1342
1357static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlags flags, Axis axis, StationID *station, RailType rt, std::vector<Train *> &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
1358{
1360 bool length_price_ready = true;
1361 uint8_t tracknum = 0;
1362 int allowed_z = -1;
1363 for (TileIndex cur_tile : tile_area) {
1364 /* Clear the land below the station. */
1365 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1366 if (ret.Failed()) return ret;
1367
1368 /* Only add _price[Price::BuildStationRailLength] once for each valid plat_len. */
1369 if (tracknum == numtracks) {
1370 length_price_ready = true;
1371 tracknum = 0;
1372 } else {
1373 tracknum++;
1374 }
1375
1376 /* AddCost for new or rotated rail stations. */
1377 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1378 cost.AddCost(ret.GetCost());
1380 cost.AddCost(RailBuildCost(rt));
1381
1382 if (length_price_ready) {
1384 length_price_ready = false;
1385 }
1386 }
1387 }
1388
1389 return cost;
1390}
1391
1399{
1400 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1401 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlag::Pylons : StationSpec::TileFlags{};
1402 return statspec->tileflags[gfx];
1403}
1404
1411{
1412 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1416}
1417
1432CommandCost CmdBuildRailStation(DoCommandFlags flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
1433{
1434 /* Does the authority allow this? */
1435 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1436 if (ret.Failed()) return ret;
1437
1438 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1439
1440 /* Check if the given station class is valid */
1441 if (spec_class.base() >= StationClass::GetClassCount()) return CMD_ERROR;
1442 const StationClass *cls = StationClass::Get(spec_class);
1443 if (IsWaypointClass(*cls)) return CMD_ERROR;
1444 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1445 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1446
1447 int w_org, h_org;
1448 if (axis == Axis::X) {
1449 w_org = plat_len;
1450 h_org = numtracks;
1451 } else {
1452 h_org = plat_len;
1453 w_org = numtracks;
1454 }
1455
1456 /* Check if the first tile and the last tile are valid */
1457 if (!IsValidTile(tile_org) || TileAddWrap(tile_org, w_org - 1, h_org - 1) == INVALID_TILE) return CMD_ERROR;
1458
1459 bool reuse = (station_to_join != NEW_STATION);
1460 if (!reuse) station_to_join = StationID::Invalid();
1461 bool distant_join = (station_to_join != StationID::Invalid());
1462
1463 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1464
1465 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1466
1467 /* these values are those that will be stored in train_tile and station_platforms */
1468 TileArea new_location(tile_org, w_org, h_org);
1469 ret = CheckStationSpread({}, new_location);
1470 if (ret.Failed()) return ret;
1471
1472 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1473 StationID est = StationID::Invalid();
1474 std::vector<Train *> affected_vehicles;
1475 /* Add construction and clearing expenses. */
1476 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1477 if (cost.Failed()) return cost;
1478
1479 Station *st = nullptr;
1480 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1481 if (ret.Failed()) return ret;
1482
1483 ret = BuildStationPart(&st, flags, reuse, new_location, StationNaming::Rail);
1484 if (ret.Failed()) return ret;
1485
1486 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1487 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1488 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1489
1490 RailStationTileLayout<StationType::Rail> stl{statspec, numtracks, plat_len};
1491 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1492 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1493 /* Don't check the layout if there's no bridge above anyway. */
1494 if (!IsBridgeAbove(tile)) continue;
1495
1496 StationGfx gfx = *it + to_underlying(axis);
1497 if (statspec != nullptr) {
1498 uint32_t platinfo = GetPlatformInfo(gfx, numtracks, plat_len, i, j, false);
1499 /* As the station is not yet completely finished, the station does not yet exist. */
1500 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, INVALID_TILE);
1501 if (callback != CALLBACK_FAILED && callback <= UINT8_MAX) gfx = (callback & ~1) + to_underlying(axis);
1502 }
1503
1504 ret = IsRailStationBridgeAboveOk(tile, statspec, StationType::Rail, gfx);
1505 if (ret.Failed()) return ret;
1506 }
1507 }
1508
1509 /* Check if we can allocate a custom stationspec to this station */
1510 auto specindex = AllocateSpecToStation(statspec, st);
1511 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
1512
1513 if (statspec != nullptr) {
1514 /* Perform NewStation checks */
1515
1516 /* Check if the station size is permitted */
1517 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1518 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_LENGTH);
1519
1520 /* Check if the station is buildable */
1522 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1524 }
1525 }
1526
1527 if (flags.Test(DoCommandFlag::Execute)) {
1528 st->AddFacility(StationFacility::Train, new_location.tile);
1529
1530 st->train_station.Add(new_location);
1531 st->spread.Add(new_location);
1532
1533 if (specindex.has_value()) AssignSpecToStation(statspec, st, *specindex);
1534 if (statspec != nullptr) {
1535 /* Include this station spec's animation trigger bitmask
1536 * in the station's cached copy. */
1537 st->cached_anim_triggers.Set(statspec->animation.triggers);
1538 }
1539
1540 Track track = AxisToTrack(axis);
1541 Company *c = Company::Get(st->owner);
1542 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1543 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1544 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1545 /* Check for trains having a reservation for this tile. */
1547 if (v != nullptr) {
1548 affected_vehicles.push_back(v);
1550 }
1551 }
1552
1553 /* Railtype can change when overbuilding. */
1554 if (IsRailStationTile(tile)) {
1555 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1557 }
1558
1559 /* Remove animation if overbuilding */
1560 DeleteAnimatedTile(tile);
1561 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1562
1563 MakeRailStation(tile, st->owner, st->index, axis, *it, rt);
1564 /* Free the spec if we overbuild something */
1565 DeallocateSpecFromStation(st, old_specindex);
1566 if (statspec == nullptr) DeleteNewGRFInspectWindow(GrfSpecFeature::Stations, tile);
1567
1568 SetCustomStationSpecIndex(tile, *specindex);
1569 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1570 SetAnimationFrame(tile, 0);
1571
1572 if (statspec != nullptr) {
1573 uint32_t platinfo = GetPlatformInfo(*it + to_underlying(axis), numtracks, plat_len, i, j, false);
1574
1575 /* As the station is not yet completely finished, the station does not yet exist. */
1576 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1577 if (callback != CALLBACK_FAILED) {
1578 if (callback <= UINT8_MAX) {
1579 SetStationGfx(tile, (callback & ~1) + to_underlying(axis));
1580 } else {
1582 }
1583 }
1584
1585 /* Trigger station animation -- after building? */
1586 TriggerStationAnimation(st, tile, StationAnimationTrigger::Built);
1587 }
1588
1589 SetRailStationTileFlags(tile, statspec);
1590
1591 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1593 }
1594 AddTrackToSignalBuffer(tile_track, track, _current_company);
1595 YapfNotifyTrackLayoutChange(tile_track, track);
1596 }
1597
1598 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1599 /* Restore reservations of trains. */
1600 RestoreTrainReservation(affected_vehicles[i]);
1601 }
1602
1603 /* Check whether we need to expand the reservation of trains already on the station. */
1604 TileArea update_reservation_area;
1605 if (axis == Axis::X) {
1606 update_reservation_area = TileArea(tile_org, 1, numtracks);
1607 } else {
1608 update_reservation_area = TileArea(tile_org, numtracks, 1);
1609 }
1610
1611 for (TileIndex tile : update_reservation_area) {
1612 /* Don't even try to make eye candy parts reserved. */
1613 if (IsStationTileBlocked(tile)) continue;
1614
1615 DiagDirection dir = AxisToDiagDir(axis);
1616 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1617 TileIndex platform_begin = tile;
1618 TileIndex platform_end = tile;
1619
1620 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1621 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1622 platform_begin = next_tile;
1623 }
1624 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1625 platform_end = next_tile;
1626 }
1627
1628 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1629 bool reservation = false;
1630 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1631 reservation = HasStationReservation(t);
1632 }
1633
1634 if (reservation) {
1635 SetRailStationPlatformReservation(platform_begin, dir, true);
1636 }
1637 }
1638
1639 st->MarkTilesDirty(false);
1641 }
1642
1643 return cost;
1644}
1645
1646static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1647{
1648restart:
1649
1650 /* too small? */
1651 if (ta.w != 0 && ta.h != 0) {
1652 /* check the left side, x = constant, y changes */
1653 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1654 /* the left side is unused? */
1655 if (++i == ta.h) {
1656 ta.tile += TileDiffXY(1, 0);
1657 ta.w--;
1658 goto restart;
1659 }
1660 }
1661
1662 /* check the right side, x = constant, y changes */
1663 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1664 /* the right side is unused? */
1665 if (++i == ta.h) {
1666 ta.w--;
1667 goto restart;
1668 }
1669 }
1670
1671 /* check the upper side, y = constant, x changes */
1672 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1673 /* the left side is unused? */
1674 if (++i == ta.w) {
1675 ta.tile += TileDiffXY(0, 1);
1676 ta.h--;
1677 goto restart;
1678 }
1679 }
1680
1681 /* check the lower side, y = constant, x changes */
1682 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1683 /* the left side is unused? */
1684 if (++i == ta.w) {
1685 ta.h--;
1686 goto restart;
1687 }
1688 }
1689 } else {
1690 ta.Clear();
1691 }
1692
1693 return ta;
1694}
1695
1701{
1702 static constexpr auto func = [](BaseStation *st, TileIndex tile) { return IsTileType(tile, TileType::Station) && GetStationIndex(tile) == st->index; };
1703 st->spread = MakeStationAreaSmaller(st, st->spread, func);
1704}
1705
1706static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1707{
1708 return st->TileBelongsToRailStation(tile);
1709}
1710
1711static void MakeRailStationAreaSmaller(BaseStation *st)
1712{
1713 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1714}
1715
1716static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1717{
1718 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1719}
1720
1721static void MakeShipStationAreaSmaller(Station *st)
1722{
1723 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1724 UpdateStationDockingTiles(st);
1725}
1726
1727static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1728{
1729 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1730}
1731
1732void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1733{
1734 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1735}
1736
1747template <class T>
1748CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlags flags, Money removal_cost, bool keep_rail)
1749{
1750 /* Count of the number of tiles removed */
1751 int quantity = 0;
1753 /* Accumulator for the errors seen during clearing. If no errors happen,
1754 * and the quantity is 0 there is no station. Otherwise it will be one
1755 * of the other error that got accumulated. */
1756 CommandCost error;
1757
1758 /* Do the action for every tile into the area */
1759 for (TileIndex tile : ta) {
1760 /* Make sure the specified tile is a rail station */
1761 if (!HasStationTileRail(tile)) continue;
1762
1763 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1765 error.AddCost(std::move(ret));
1766 if (error.Failed()) continue;
1767
1768 /* Check ownership of station */
1769 T *st = T::GetByTile(tile);
1770 if (st == nullptr) continue;
1771
1773 ret = CheckOwnership(st->owner);
1774 error.AddCost(std::move(ret));
1775 if (error.Failed()) continue;
1776 }
1777
1778 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1779 quantity++;
1780
1781 if (keep_rail || IsStationTileBlocked(tile)) {
1782 /* Don't refund the 'steel' of the track when we keep the
1783 * rail, or when the tile didn't have any rail at all. */
1784 total_cost.AddCost(-_price[Price::ClearRail]);
1785 }
1786
1787 if (flags.Test(DoCommandFlag::Execute)) {
1788 /* read variables before the station tile is removed */
1789 uint specindex = GetCustomStationSpecIndex(tile);
1790 Track track = GetRailStationTrack(tile);
1791 Owner owner = GetTileOwner(tile);
1792 RailType rt = GetRailType(tile);
1793 Train *v = nullptr;
1794
1795 if (HasStationReservation(tile)) {
1796 v = GetTrainForReservation(tile, track);
1797 if (v != nullptr) FreeTrainReservation(v);
1798 }
1799
1800 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1801 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1802
1803 DoClearSquare(tile);
1805 if (build_rail) MakeRailNormal(tile, owner, track, rt);
1806 Company::Get(owner)->infrastructure.station--;
1808
1809 st->tile_waiting_random_triggers.erase(tile);
1810 AddTrackToSignalBuffer(tile, track, owner);
1811 YapfNotifyTrackLayoutChange(tile, track);
1812
1813 DeallocateSpecFromStation(st, specindex);
1814
1815 include(affected_stations, st);
1816
1817 if (v != nullptr) RestoreTrainReservation(v);
1818 }
1819 }
1820
1821 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1822
1823 for (T *st : affected_stations) {
1824
1825 /* now we need to make the "spanned" area of the railway station smaller
1826 * if we deleted something at the edges.
1827 * we also need to adjust train_tile. */
1828 MakeRailStationAreaSmaller(st);
1830 UpdateStationSignCoord(st);
1831
1832 /* if we deleted the whole station, delete the train facility. */
1833 if (st->train_station.IsEmpty()) {
1835 SetWindowClassesDirty(WindowClass::VehicleOrders);
1836 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1837 MarkCatchmentTilesDirty();
1838 st->UpdateVirtCoord();
1840 }
1841 }
1842
1843 total_cost.AddCost(quantity * removal_cost);
1844 return total_cost;
1845}
1846
1857{
1858 if (end == 0) end = start;
1859 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1860
1861 TileArea ta(start, end);
1862 std::vector<Station *> affected_stations;
1863
1864 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearStationRail], keep_rail);
1865 if (ret.Failed()) return ret;
1866
1867 /* Do all station specific functions here. */
1868 for (Station *st : affected_stations) {
1869
1870 if (st->train_station.IsEmpty()) SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1871 st->MarkTilesDirty(false);
1872 MarkCatchmentTilesDirty();
1873 st->RecomputeCatchment();
1874 }
1875
1876 /* Now apply the rail cost to the number that we deleted */
1877 return ret;
1878}
1879
1890{
1891 if (end == 0) end = start;
1892 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1893
1894 TileArea ta(start, end);
1895 std::vector<Waypoint *> affected_stations;
1896
1897 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearWaypointRail], keep_rail);
1898}
1899
1900
1909template <class T>
1910CommandCost RemoveRailStation(T *st, DoCommandFlags flags, Money removal_cost)
1911{
1912 /* Current company owns the station? */
1914 CommandCost ret = CheckOwnership(st->owner);
1915 if (ret.Failed()) return ret;
1916 }
1917
1918 /* determine width and height of platforms */
1919 TileArea ta = st->train_station;
1920
1921 assert(ta.w != 0 && ta.h != 0);
1922
1924 /* clear all areas of the station */
1925 for (TileIndex tile : ta) {
1926 /* only remove tiles that are actually train station tiles */
1927 if (st->TileBelongsToRailStation(tile)) {
1928 std::vector<T*> affected_stations; // dummy
1929 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1930 if (ret.Failed()) return ret;
1931 cost.AddCost(ret.GetCost());
1932 }
1933 }
1934
1935 return cost;
1936}
1937
1945{
1946 /* if there is flooding, remove platforms tile by tile */
1948 return Command<Commands::RemoveFromRailStation>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1949 }
1950
1951 Station *st = Station::GetByTile(tile);
1953
1955
1956 return cost;
1957}
1958
1966{
1967 /* if there is flooding, remove waypoints tile by tile */
1969 return Command<Commands::RemoveFromRailWaypoint>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1970 }
1971
1973}
1974
1975
1981static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1982{
1983 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1984
1985 if (*primary_stop == nullptr) {
1986 /* we have no roadstop of the type yet, so write a "primary stop" */
1987 return primary_stop;
1988 } else {
1989 /* there are stops already, so append to the end of the list */
1990 RoadStop *stop = *primary_stop;
1991 while (stop->next != nullptr) stop = stop->next;
1992 return &stop->next;
1993 }
1994}
1995
1996static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
1997CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
1998
2008static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
2009{
2010 return FindJoiningBaseStation<Station>(STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST, existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
2011}
2012
2027CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlags flags, bool is_drive_through, StationType station_type, const RoadStopSpec *roadstopspec, Axis axis, DiagDirection ddir, StationID *station, RoadType rt, Money unit_cost)
2028{
2029 DiagDirections invalid_dirs = is_drive_through ? AxisToDiagDirs(axis) : ddir;
2030
2031 /* Check every tile in the area. */
2032 int allowed_z = -1;
2034 for (TileIndex cur_tile : tile_area) {
2035 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, roadstopspec, flags, invalid_dirs, is_drive_through, station_type, axis, station, rt);
2036 if (ret.Failed()) return ret;
2037
2038 bool is_preexisting_roadstop = IsTileType(cur_tile, TileType::Station) && IsAnyRoadStop(cur_tile);
2039
2040 /* Only add costs if a stop doesn't already exist in the location */
2041 if (!is_preexisting_roadstop) {
2042 cost.AddCost(ret.GetCost());
2043 cost.AddCost(unit_cost);
2044 }
2045 }
2046
2047 return cost;
2048}
2049
2066CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
2067 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
2068{
2069 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= RoadStopType::End) return CMD_ERROR;
2070 bool reuse = (station_to_join != NEW_STATION);
2071 if (!reuse) station_to_join = StationID::Invalid();
2072 bool distant_join = (station_to_join != StationID::Invalid());
2073
2074 /* Check if the given station class is valid */
2075 if (spec_class.base() >= RoadStopClass::GetClassCount()) return CMD_ERROR;
2076 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
2077 if (IsWaypointClass(*cls)) return CMD_ERROR;
2078 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
2079
2080 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
2081 if (roadstopspec != nullptr) {
2082 if (stop_type == RoadStopType::Truck && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2083 if (stop_type == RoadStopType::Bus && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2084 if (!is_drive_through && roadstopspec->flags.Test(RoadStopSpecFlag::DriveThroughOnly)) return CMD_ERROR;
2085 }
2086
2087 /* Check if the requested road stop is too big */
2088 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2089 /* Check for incorrect width / length. */
2090 if (width == 0 || length == 0) return CMD_ERROR;
2091 /* Check if the first tile and the last tile are valid */
2092 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
2093
2094 TileArea roadstop_area(tile, width, length);
2095 if (CommandCost ret = CheckStationSpread({}, roadstop_area); ret.Failed()) return ret;
2096
2097 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2098
2099 /* Trams only have drive through stops */
2100 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2101
2102 Axis axis = DiagDirToAxis(ddir);
2103
2105 if (ret.Failed()) return ret;
2106
2107 bool is_truck_stop = stop_type != RoadStopType::Bus;
2108
2109 /* Total road stop cost. */
2110 Money unit_cost;
2111 if (roadstopspec != nullptr) {
2112 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus);
2113 } else {
2114 unit_cost = _price[is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus];
2115 }
2116 StationID est = StationID::Invalid();
2117 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? StationType::Truck : StationType::Bus, roadstopspec, axis, ddir, &est, rt, unit_cost);
2118 if (cost.Failed()) return cost;
2119
2120 Station *st = nullptr;
2121 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2122 if (ret.Failed()) return ret;
2123
2124 /* Check if this number of road stops can be allocated. */
2125 if (!RoadStop::CanAllocateItem(static_cast<size_t>(roadstop_area.w) * roadstop_area.h)) return CommandCost(is_truck_stop ? STR_ERROR_TOO_MANY_TRUCK_STOPS : STR_ERROR_TOO_MANY_BUS_STOPS);
2126
2127 ret = BuildStationPart(&st, flags, reuse, roadstop_area, StationNaming::Road);
2128 if (ret.Failed()) return ret;
2129
2130 /* Check if we can allocate a custom stationspec to this station */
2131 auto specindex = AllocateSpecToRoadStop(roadstopspec, st);
2132 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
2133
2134 if (roadstopspec != nullptr) {
2135 /* Perform NewGRF checks */
2136
2137 /* Check if the road stop is buildable */
2138 if (roadstopspec->callback_mask.Test(RoadStopCallbackMask::Avail)) {
2139 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? StationType::Truck : StationType::Bus, 0);
2140 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2141 }
2142 }
2143
2144 if (flags.Test(DoCommandFlag::Execute)) {
2145 if (specindex.has_value()) AssignSpecToRoadStop(roadstopspec, st, *specindex);
2146 /* Check every tile in the area. */
2147 for (TileIndex cur_tile : roadstop_area) {
2148 /* Get existing road types and owners before any tile clearing */
2149 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Road) : INVALID_ROADTYPE;
2150 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Tram) : INVALID_ROADTYPE;
2151 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Road) : _current_company;
2152 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Tram) : _current_company;
2153
2154 if (IsTileType(cur_tile, TileType::Station) && IsStationRoadStop(cur_tile)) {
2155 RemoveRoadStop(cur_tile, flags, *specindex);
2156 }
2157
2158 if (roadstopspec != nullptr) {
2159 /* Include this road stop spec's animation trigger bitmask
2160 * in the station's cached copy. */
2161 st->cached_roadstop_anim_triggers.Set(roadstopspec->animation.triggers);
2162 }
2163
2164 RoadStop *road_stop = RoadStop::Create(cur_tile);
2165 /* Insert into linked list of RoadStops. */
2166 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2167 *currstop = road_stop;
2168
2169 if (is_truck_stop) {
2170 st->truck_station.Add(cur_tile);
2171 } else {
2172 st->bus_station.Add(cur_tile);
2173 }
2174
2175 /* Initialize an empty station. */
2176 st->AddFacility(is_truck_stop ? StationFacility::TruckStop : StationFacility::BusStop, cur_tile);
2177
2178 st->spread.Add(cur_tile);
2179
2180 RoadStopType rs_type = is_truck_stop ? RoadStopType::Truck : RoadStopType::Bus;
2181 if (is_drive_through) {
2182 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2183 * bits first. */
2184 if (IsNormalRoadTile(cur_tile)) {
2185 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Road).Count()));
2186 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Tram).Count()));
2187 }
2188
2189 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2190 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2191
2192 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == RoadStopType::Bus ? StationType::Bus : StationType::Truck), road_rt, tram_rt, axis);
2193 road_stop->MakeDriveThrough();
2194 } else {
2195 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2196 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2197 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2198 }
2201 Company::Get(st->owner)->infrastructure.station++;
2202
2203 SetCustomRoadStopSpecIndex(cur_tile, *specindex);
2204 if (roadstopspec != nullptr) {
2205 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2206 TriggerRoadStopAnimation(st, cur_tile, StationAnimationTrigger::Built);
2207 }
2208
2209 MarkTileDirtyByTile(cur_tile);
2210 }
2211
2212 if (st != nullptr) {
2214 }
2215 }
2216 return cost;
2217}
2218
2226static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2227{
2228 Station *st = Station::GetByTile(tile);
2229
2231 CommandCost ret = CheckOwnership(st->owner);
2232 if (ret.Failed()) return ret;
2233 }
2234
2235 bool is_truck = IsTruckStop(tile);
2236
2237 RoadStop **primary_stop;
2238 RoadStop *cur_stop;
2239 if (is_truck) { // truck stop
2240 primary_stop = &st->truck_stops;
2241 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Truck);
2242 } else {
2243 primary_stop = &st->bus_stops;
2244 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Bus);
2245 }
2246
2247 assert(cur_stop != nullptr);
2248
2249 /* don't do the check for drive-through road stops when company bankrupts */
2251 /* remove the 'going through road stop' status from all vehicles on that tile */
2252 if (flags.Test(DoCommandFlag::Execute)) {
2253 for (Vehicle *v : VehiclesOnTile(tile)) {
2254 if (v->type != VehicleType::Road) continue;
2255 /* Okay... we are a road vehicle on a drive through road stop.
2256 * But that road stop has just been removed, so we need to make
2257 * sure we are in a valid state... however, vehicles can also
2258 * turn on road stop tiles, so only clear the 'road stop' state
2259 * bits and only when the state was 'in road stop', otherwise
2260 * we'll end up clearing the turn around bits. */
2263 }
2264 }
2265 } else {
2267 if (ret.Failed()) return ret;
2268 }
2269
2270 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2271
2272 if (flags.Test(DoCommandFlag::Execute)) {
2273 if (*primary_stop == cur_stop) {
2274 /* removed the first stop in the list */
2275 *primary_stop = cur_stop->next;
2276 /* removed the only stop? */
2277 if (*primary_stop == nullptr) {
2279 SetWindowClassesDirty(WindowClass::VehicleOrders);
2280 }
2281 } else {
2282 /* tell the predecessor in the list to skip this stop */
2283 RoadStop *pred = *primary_stop;
2284 while (pred->next != cur_stop) pred = pred->next;
2285 pred->next = cur_stop->next;
2286 }
2287
2288 /* Update company infrastructure counts. */
2289 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2290 RoadType rt = GetRoadType(tile, rtt);
2292 }
2293
2294 Company::Get(st->owner)->infrastructure.station--;
2296
2297 uint specindex = GetCustomRoadStopSpecIndex(tile);
2298
2300
2301 if (IsDriveThroughStopTile(tile)) {
2302 /* Clears the tile for us */
2303 cur_stop->ClearDriveThrough();
2304 DeleteAnimatedTile(tile);
2305 } else {
2306 DoClearSquare(tile);
2307 }
2308
2309 delete cur_stop;
2310
2311 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2312 * this station, then look for any currently heading to the tile. */
2313 StationID station_id = st->index;
2315 [](const Vehicle *v) { return v->type == VehicleType::Road; },
2316 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2317 [station_id, tile](Vehicle *v) {
2318 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2319 v->SetDestTile(v->GetOrderStationLocation(station_id));
2320 }
2321 }
2322 );
2323
2325
2326 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? StationType::Truck: StationType::Bus);
2327
2328 st->tile_waiting_random_triggers.erase(tile);
2329 st->RemoveRoadStopTileData(tile);
2330 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2331
2332 /* Update the tile area of the truck/bus stop */
2333 if (is_truck) {
2334 st->truck_station.Clear();
2335 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2336 } else {
2337 st->bus_station.Clear();
2338 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2339 }
2340 }
2341
2343 return CommandCost(ExpensesType::Construction, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2344}
2345
2353CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2354{
2355 Waypoint *wp = Waypoint::GetByTile(tile);
2356
2358 CommandCost ret = CheckOwnership(wp->owner);
2359 if (ret.Failed()) return ret;
2360 }
2361
2362 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2363 if (!flags.Test(DoCommandFlag::Bankrupt)) {
2365 if (ret.Failed()) return ret;
2366 }
2367
2368 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2369
2370 if (flags.Test(DoCommandFlag::Execute)) {
2371 /* Update company infrastructure counts. */
2372 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2373 RoadType rt = GetRoadType(tile, rtt);
2375 }
2376
2377 Company::Get(wp->owner)->infrastructure.station--;
2379
2380 uint specindex = GetCustomRoadStopSpecIndex(tile);
2381
2383
2384 DoClearSquare(tile);
2385
2387
2388 wp->tile_waiting_random_triggers.erase(tile);
2389 wp->RemoveRoadStopTileData(tile);
2390 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2391
2392 if (replacement_spec_index < 0) {
2393 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2394
2395 UpdateStationSignCoord(wp);
2396
2397 /* if we deleted the whole waypoint, delete the road facility. */
2398 if (wp->road_waypoint_area.IsEmpty()) {
2400 SetWindowWidgetDirty(WindowClass::StationView, wp->index, WID_SV_ROADVEHS);
2401 wp->UpdateVirtCoord();
2403 }
2404 }
2405 }
2406
2408}
2409
2418static CommandCost RemoveGenericRoadStop(DoCommandFlags flags, const TileArea &roadstop_area, bool road_waypoint, bool remove_road)
2419{
2421 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2422 bool had_success = false;
2423
2424 for (TileIndex cur_tile : roadstop_area) {
2425 /* Make sure the specified tile is a road stop of the correct type */
2426 if (!IsTileType(cur_tile, TileType::Station) || !IsAnyRoadStop(cur_tile) || IsRoadWaypoint(cur_tile) != road_waypoint) continue;
2427
2428 /* Save information on to-be-restored roads before the stop is removed. */
2429 RoadBits road_bits{};
2432 if (IsDriveThroughStopTile(cur_tile)) {
2433 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2434 road_type[rtt] = GetRoadType(cur_tile, rtt);
2435 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2436 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2437 /* If we don't want to preserve our roads then restore only roads of others. */
2438 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2439 }
2440 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2441 }
2442
2443 CommandCost ret;
2444 if (road_waypoint) {
2445 ret = RemoveRoadWaypointStop(cur_tile, flags);
2446 } else {
2447 ret = RemoveRoadStop(cur_tile, flags);
2448 }
2449 if (ret.Failed()) {
2450 last_error = std::move(ret);
2451 continue;
2452 }
2453 cost.AddCost(ret.GetCost());
2454 had_success = true;
2455
2456 /* Restore roads. */
2458 MakeRoadNormal(cur_tile, road_bits, road_type[RoadTramType::Road], road_type[RoadTramType::Tram], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2459 road_owner[RoadTramType::Road], road_owner[RoadTramType::Tram]);
2460
2461 /* Update company infrastructure counts. */
2462 int count = road_bits.Count();
2465 }
2466 }
2467
2468 return had_success ? cost : last_error;
2469}
2470
2481CommandCost CmdRemoveRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2482{
2483 if (stop_type >= RoadStopType::End) return CMD_ERROR;
2484 /* Check for incorrect width / height. */
2485 if (width == 0 || height == 0) return CMD_ERROR;
2486 /* Check if the first tile and the last tile are valid */
2487 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2488 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2489 if (remove_road && flags.Test(DoCommandFlag::Bankrupt)) return CMD_ERROR;
2490
2491 TileArea roadstop_area(tile, width, height);
2492
2493 return RemoveGenericRoadStop(flags, roadstop_area, false, remove_road);
2494}
2495
2504{
2505 if (end == 0) end = start;
2506 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2507
2508 TileArea roadstop_area(start, end);
2509
2510 return RemoveGenericRoadStop(flags, roadstop_area, true, false);
2511}
2512
2521uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2522{
2523 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2524 * So no need to go any further*/
2525 if (as->noise_level < 2) return as->noise_level;
2526
2527 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2528 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2529 * Basically, it says that the less tolerant a town is, the bigger the distance before
2530 * an actual decrease can be granted */
2531 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2532
2533 /* now, we want to have the distance segmented using the distance judged bareable by town
2534 * This will give us the coefficient of reduction the distance provides. */
2535 uint noise_reduction = distance / town_tolerance_distance;
2536
2537 /* If the noise reduction equals the airport noise itself, don't give it for free.
2538 * Otherwise, simply reduce the airport's level. */
2539 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2540}
2541
2553{
2554 assert(Town::GetNumItems() > 0);
2555
2556 Town *nearest = nullptr;
2557
2558 auto width = as->size_x;
2559 auto height = as->size_y;
2560 if (rotation == Direction::E || rotation == Direction::W) std::swap(width, height);
2561
2562 uint perimeter_min_x = TileX(tile);
2563 uint perimeter_min_y = TileY(tile);
2564 uint perimeter_max_x = perimeter_min_x + width - 1;
2565 uint perimeter_max_y = perimeter_min_y + height - 1;
2566
2567 mindist = UINT_MAX - 1; // prevent overflow
2568
2569 for (; *iter != INVALID_TILE; ++iter) {
2570 TileIndex cur_tile = *iter;
2571 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2572 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2573 if (TileX(cur_tile) == perimeter_min_x || TileX(cur_tile) == perimeter_max_x || TileY(cur_tile) == perimeter_min_y || TileY(cur_tile) == perimeter_max_y) {
2574 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2575 if (t == nullptr) continue;
2576
2577 uint dist = DistanceManhattan(t->xy, cur_tile);
2578 if (dist == mindist && t->index < nearest->index) nearest = t;
2579 if (dist < mindist) {
2580 nearest = t;
2581 mindist = dist;
2582 }
2583 }
2584 }
2585
2586 return nearest;
2587}
2588
2596static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2597{
2599}
2600
2601
2604{
2605 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2606
2607 for (const Station *st : Station::Iterate()) {
2608 if (!st->airport.IsEmpty() && st->airport.type != AT_OILRIG) {
2609 uint dist;
2610 Town *nearest = AirportGetNearestTown(st, dist);
2611 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2612 }
2613 }
2614}
2615
2626CommandCost CmdBuildAirport(DoCommandFlags flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2627{
2628 bool reuse = (station_to_join != NEW_STATION);
2629 if (!reuse) station_to_join = StationID::Invalid();
2630 bool distant_join = (station_to_join != StationID::Invalid());
2631
2632 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2633
2634 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2635
2637 if (ret.Failed()) return ret;
2638
2639 /* Check if a valid, buildable airport was chosen for construction */
2640 const AirportSpec *as = AirportSpec::Get(airport_type);
2641 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2642 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2643
2644 Direction rotation = as->layouts[layout].rotation;
2645 int w = as->size_x;
2646 int h = as->size_y;
2647 if (rotation == Direction::E || rotation == Direction::W) std::swap(w, h);
2648 TileArea airport_area = TileArea(tile, w, h);
2649
2650 ret = CheckStationSpread({}, airport_area);
2651 if (ret.Failed()) return ret;
2652
2653 CommandCost cost = CheckFlatLandAirport(AirportTileTableIterator{as->layouts[layout].tiles, tile, true}, flags);
2654 if (cost.Failed()) return cost;
2655
2656 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2657 uint dist;
2658 Town *nearest = AirportGetNearestTown(as, rotation, tile, AirportTileTableIterator{as->layouts[layout].tiles, tile, false}, dist);
2659 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2660
2661 /* Check if local auth would allow a new airport */
2662 StringID authority_refuse_message = STR_NULL;
2663 Town *authority_refuse_town = nullptr;
2664
2665 if (_settings_game.economy.station_noise_level) {
2666 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2667 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2668 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2669 authority_refuse_town = nearest;
2670 }
2671 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2672 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2673 uint num = 0;
2674 for (const Station *st : Station::Iterate()) {
2675 if (st->town == t && st->facilities.Test(StationFacility::Airport) && st->airport.type != AT_OILRIG) num++;
2676 }
2677 if (num >= 2) {
2678 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2679 authority_refuse_town = t;
2680 }
2681 }
2682
2683 if (authority_refuse_message != STR_NULL) {
2684 return CommandCostWithParam(authority_refuse_message, authority_refuse_town->index);
2685 }
2686
2687 Station *st = nullptr;
2688 ret = FindJoiningStation(StationID::Invalid(), station_to_join, allow_adjacent, airport_area, &st);
2689 if (ret.Failed()) return ret;
2690
2691 /* Distant join */
2692 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2693
2694 ret = BuildStationPart(&st, flags, reuse, airport_area, GetAirport(airport_type)->flags.Test(AirportFTAClass::Flag::Airplanes) ? StationNaming::Airport : StationNaming::Heliport);
2695 if (ret.Failed()) return ret;
2696
2697 if (st != nullptr && !st->airport.IsEmpty()) {
2698 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2699 }
2700
2701 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2703 }
2704
2705 if (flags.Test(DoCommandFlag::Execute)) {
2706 /* Always add the noise, so there will be no need to recalculate when option toggles */
2707 nearest->noise_reached += newnoise_level;
2708
2710 st->airport.type = airport_type;
2711 st->airport.layout = layout;
2712 st->airport.blocks = {};
2713 st->airport.rotation = rotation;
2714
2715 st->spread.Add(airport_area);
2716
2717 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2718 StationGfx gfx = static_cast<StationGfx>(iter.GetAirportGfx());
2719
2720 MakeAirport(*iter, st->owner, st->index, gfx, WaterClass::Invalid);
2721 SetStationTileRandomBits(*iter, GB(Random(), 0, 4));
2722 st->airport.Add(*iter);
2723
2725 }
2726
2727 /* Only call the animation trigger after all tiles have been built */
2728 for (AirportTileTableIterator iter{as->layouts[layout].tiles, tile, false}; *iter != INVALID_TILE; ++iter) {
2729 TriggerAirportTileAnimation(st, *iter, AirportAnimationTrigger::Built);
2730 }
2731
2733
2734 Company::Get(st->owner)->infrastructure.airport++;
2735
2737 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2738
2739 if (_settings_game.economy.station_noise_level) {
2740 SetWindowDirty(WindowClass::TownView, nearest->index);
2741 }
2742 }
2743
2744 return cost;
2745}
2746
2754{
2755 Station *st = Station::GetByTile(tile);
2756
2758 CommandCost ret = CheckOwnership(st->owner);
2759 if (ret.Failed()) return ret;
2760 }
2761
2762 tile = st->airport.tile;
2763
2765
2766 for (const Aircraft *a : Aircraft::Iterate()) {
2767 if (!a->IsNormalAircraft()) continue;
2768 if (a->targetairport == st->index && a->state != FLYING) {
2769 return CommandCost(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2770 }
2771 }
2772
2773 if (flags.Test(DoCommandFlag::Execute)) {
2774 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2775 TileIndex tile_cur = st->airport.GetHangarTile(i);
2776 OrderBackup::Reset(tile_cur, false);
2777 CloseWindowById(WindowClass::VehicleDepot, tile_cur);
2778 }
2779
2780 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2781 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2782 * need of recalculation */
2783 uint dist;
2784 Town *nearest = AirportGetNearestTown(st, dist);
2786
2787 if (_settings_game.economy.station_noise_level) {
2788 SetWindowDirty(WindowClass::TownView, nearest->index);
2789 }
2790 }
2791
2792 for (TileIndex tile_cur : st->airport) {
2793 if (!st->TileBelongsToAirport(tile_cur)) continue;
2794
2795 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2796 if (ret.Failed()) return ret;
2797
2799
2800 if (flags.Test(DoCommandFlag::Execute)) {
2801 DoClearSquare(tile_cur);
2803 }
2804 }
2805
2806 if (flags.Test(DoCommandFlag::Execute)) {
2807 /* Clear the persistent storage. */
2808 delete st->airport.psa;
2809
2811
2812 st->airport.Clear();
2814 SetWindowClassesDirty(WindowClass::VehicleOrders);
2815
2816 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2817
2818 Company::Get(st->owner)->infrastructure.airport--;
2819
2821
2823 }
2824
2825 return cost;
2826}
2827
2835{
2836 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2837 Station *st = Station::Get(station_id);
2838
2840
2841 CommandCost ret = CheckOwnership(st->owner);
2842 if (ret.Failed()) return ret;
2843
2844 if (flags.Test(DoCommandFlag::Execute)) {
2846 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_CLOSE_AIRPORT);
2847 }
2848 return CommandCost();
2849}
2850
2858bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2859{
2860 for (const OrderList *orderlist : OrderList::Iterate()) {
2861 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2862 assert(v != nullptr);
2863 if ((v->owner == company) != include_company) continue;
2864
2865 for (const Order &order : orderlist->GetOrders()) {
2866 if (order.GetDestination() == station && (order.IsType(OT_GOTO_STATION) || order.IsType(OT_GOTO_WAYPOINT))) {
2867 return true;
2868 }
2869 }
2870 }
2871 return false;
2872}
2873
2876 {-1, 0},
2877 { 0, 0},
2878 { 0, 0},
2879 { 0, -1}
2880}}};
2881
2885
2894CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station_to_join, bool adjacent)
2895{
2896 bool reuse = (station_to_join != NEW_STATION);
2897 if (!reuse) station_to_join = StationID::Invalid();
2898 bool distant_join = (station_to_join != StationID::Invalid());
2899
2900 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2901
2903 if (direction == DiagDirection::Invalid) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2904 direction = ReverseDiagDir(direction);
2905
2906 /* Docks cannot be placed on rapids */
2907 if (HasTileWaterGround(tile)) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2908
2910 if (ret.Failed()) return ret;
2911
2912 ret = IsDockBridgeAboveOk(tile, to_underlying(direction));
2913 if (ret.Failed()) return ret;
2914
2916 ret = Command<Commands::LandscapeClear>::Do(flags, tile);
2917 if (ret.Failed()) return ret;
2918 cost.AddCost(ret.GetCost());
2919
2920 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2921
2922 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2923 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2924 }
2925
2927 if (ret.Failed()) return ret;
2928
2929 /* Get the water class of the water tile before it is cleared.*/
2930 WaterClass wc = GetWaterClass(tile_cur);
2931
2932 bool add_cost = !IsWaterTile(tile_cur);
2933 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
2934 if (ret.Failed()) return ret;
2935 if (add_cost) cost.AddCost(ret.GetCost());
2936
2937 tile_cur += TileOffsByDiagDir(direction);
2938 if (!IsTileType(tile_cur, TileType::Water) || !IsTileFlat(tile_cur)) {
2939 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2940 }
2941
2942 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2943 _dock_w_chk[direction], _dock_h_chk[direction]);
2944
2945 /* middle */
2946 Station *st = nullptr;
2947 ret = FindJoiningStation(StationID::Invalid(), station_to_join, adjacent, dock_area, &st);
2948 if (ret.Failed()) return ret;
2949
2950 /* Distant join */
2951 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2952
2953 ret = BuildStationPart(&st, flags, reuse, dock_area, StationNaming::Dock);
2954 if (ret.Failed()) return ret;
2955
2956 if (flags.Test(DoCommandFlag::Execute)) {
2957 st->ship_station.Add(tile);
2958 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2959 st->ship_station.Add(flat_tile);
2961
2962 st->spread.Add(dock_area);
2963
2964 /* If the water part of the dock is on a canal, update infrastructure counts.
2965 * This is needed as we've cleared that tile before.
2966 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2967 * See: MakeWaterKeepingClass() */
2968 if (wc == WaterClass::Canal && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WaterClass::Canal && IsTileOwner(flat_tile, _current_company))) {
2969 Company::Get(st->owner)->infrastructure.water++;
2970 }
2971 Company::Get(st->owner)->infrastructure.station += 2;
2972
2973 MakeDock(tile, st->owner, st->index, direction, wc);
2974 UpdateStationDockingTiles(st);
2975
2977 }
2978
2979 return cost;
2980}
2981
2982void RemoveDockingTile(TileIndex t)
2983{
2984 for (DiagDirection d : EnumRange(DiagDirection::End)) {
2985 TileIndex tile = t + TileOffsByDiagDir(d);
2986 if (!IsValidTile(tile)) continue;
2987
2988 if (IsTileType(tile, TileType::Station)) {
2989 Station *st = Station::GetByTile(tile);
2990 if (st != nullptr) UpdateStationDockingTiles(st);
2991 } else if (IsTileType(tile, TileType::Industry)) {
2993 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
2994 }
2995 }
2996}
2997
3004{
3005 assert(IsValidTile(tile));
3006
3007 /* Clear and maybe re-set docking tile */
3009 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
3010 if (!IsValidTile(docking_tile)) continue;
3011
3012 if (IsPossibleDockingTile(docking_tile)) {
3013 SetDockingTile(docking_tile, false);
3014 CheckForDockingTile(docking_tile);
3015 }
3016 }
3017}
3018
3025{
3026 assert(IsDockTile(t));
3027
3028 StationGfx gfx = GetStationGfx(t);
3029 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
3030
3032 TileIndex tile = t + TileOffsByDiagDir(d);
3033 if (!IsValidTile(tile)) continue;
3034 if (!IsDockTile(tile)) continue;
3035 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
3036 }
3037
3038 return INVALID_TILE;
3039}
3040
3048{
3049 Station *st = Station::GetByTile(tile);
3050 CommandCost ret = CheckOwnership(st->owner);
3051 if (ret.Failed()) return ret;
3052
3053 if (!IsDockTile(tile)) return CMD_ERROR;
3054
3055 TileIndex tile1 = FindDockLandPart(tile);
3056 if (tile1 == INVALID_TILE) return CMD_ERROR;
3057 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
3058
3059 ret = EnsureNoVehicleOnGround(tile1);
3060 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
3061 if (ret.Failed()) return ret;
3062
3063 if (flags.Test(DoCommandFlag::Execute)) {
3064 DoClearSquare(tile1);
3065 MarkTileDirtyByTile(tile1);
3066 MakeWaterKeepingClass(tile2, st->owner);
3067
3068 MakeShipStationAreaSmaller(st);
3070
3071 if (st->ship_station.IsEmpty()) {
3072 st->docking_station.Clear();
3074 SetWindowClassesDirty(WindowClass::VehicleOrders);
3075 }
3076
3077 Company::Get(st->owner)->infrastructure.station -= 2;
3078
3080
3083
3084 for (Ship *s : Ship::Iterate()) {
3085 /* Find all ships going to our dock. */
3086 if (s->current_order.GetDestination() != st->index) {
3087 continue;
3088 }
3089
3090 /* Find ships that are marked as "loading" but are no longer on a
3091 * docking tile. Force them to leave the station (as they were loading
3092 * on the removed dock). */
3093 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3094 s->LeaveStation();
3095 }
3096
3097 /* If we no longer have a dock, mark the order as invalid and send
3098 * the ship to the next order (or, if there is none, make it
3099 * wander the world). */
3100 if (s->current_order.IsType(OT_GOTO_STATION) && !st->facilities.Test(StationFacility::Dock)) {
3101 s->SetDestTile(s->GetOrderStationLocation(st->index));
3102 }
3103 }
3104 }
3105
3107}
3108
3116{
3117 const auto &layouts = _station_display_datas[st];
3118 if (gfx >= layouts.size()) gfx &= 1;
3119 return layouts.data() + gfx;
3120}
3121
3131bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3132{
3133 bool snow_desert;
3134 switch (*ground) {
3135 case SPR_RAIL_TRACK_X:
3136 case SPR_MONO_TRACK_X:
3137 case SPR_MGLV_TRACK_X:
3138 snow_desert = false;
3139 *overlay_offset = RailTrackOffset::X;
3140 break;
3141
3142 case SPR_RAIL_TRACK_Y:
3143 case SPR_MONO_TRACK_Y:
3144 case SPR_MGLV_TRACK_Y:
3145 snow_desert = false;
3146 *overlay_offset = RailTrackOffset::Y;
3147 break;
3148
3152 snow_desert = true;
3153 *overlay_offset = RailTrackOffset::X;
3154 break;
3155
3159 snow_desert = true;
3160 *overlay_offset = RailTrackOffset::Y;
3161 break;
3162
3163 default:
3164 return false;
3165 }
3166
3167 if (ti != nullptr) {
3168 /* Decide snow/desert from tile */
3169 switch (_settings_game.game_creation.landscape) {
3171 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3172 break;
3173
3175 snow_desert = GetTropicZone(ti->tile) == TropicZone::Desert;
3176 break;
3177
3178 default:
3179 break;
3180 }
3181 }
3182
3183 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3184 return true;
3185}
3186
3193static BridgePillarFlags GetStationBlockedPillars(std::span<const BridgeableTileInfo> bridgeable_info, uint8_t layout)
3194{
3195 if (layout < std::size(bridgeable_info)) return bridgeable_info[layout].disallowed_pillars;
3196 return BRIDGEPILLARFLAGS_ALL;
3197}
3198
3208{
3209 if (statspec == nullptr || !statspec->flags.Test(StationSpecFlag::CustomFoundations)) return false;
3210
3211 /* Station has custom foundations.
3212 * Check whether the foundation continues beyond the tile's upper sides. */
3213 uint edge_info = GetFoundationSpriteBlock(ti->tile);
3214 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, gfx, edge_info);
3215 if (image == 0) return false;
3216
3218 /* Station provides extended foundations. */
3219 static constexpr uint8_t foundation_parts[] = {
3220 UINT8_MAX, UINT8_MAX, UINT8_MAX, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3221 UINT8_MAX, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3222 UINT8_MAX, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3223 7, 8, 9, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3224 };
3225 assert(ti->tileh < std::size(foundation_parts));
3226 if (foundation_parts[ti->tileh] == UINT8_MAX) return false;
3227
3228 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3229 } else {
3230 /* Draw simple foundations, built up from 8 possible foundation sprites.
3231 * Each set bit represents one of the eight composite sprites to be drawn.
3232 * 'Invalid' entries will not drawn but are included for completeness. */
3233 static constexpr uint8_t composite_foundation_parts[] = {
3234 0b0000'0000, 0b1101'0001, 0b1110'0100, 0b1110'0000, // Invalid, Invalid, Invalid, SLOPE_SW
3235 0b1100'1010, 0b1100'1001, 0b1100'0100, 0b1100'0000, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3236 0b1101'0010, 0b1001'0001, 0b1110'0100, 0b1010'0000, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3237 0b0100'1010, 0b0000'1001, 0b0100'0100, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3238 };
3239 assert(ti->tileh < std::size(composite_foundation_parts));
3240
3241 uint8_t parts = composite_foundation_parts[ti->tileh];
3242
3243 /* If foundations continue beyond the tile's upper sides then mask out the last two pieces. */
3244 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3245 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3246
3247 /* We always have to draw at least one sprite, so if we have no parts to draw fall back to default foundation. */
3248 if (parts == 0) return false;
3249
3251 for (uint i : SetBitIterator(parts)) {
3252 AddSortableSpriteToDraw(image + i, PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3253 }
3255 }
3256
3257 OffsetGroundSprite(0, -static_cast<int>(TILE_HEIGHT));
3259
3260 return true;
3261}
3262
3265{
3266 const NewGRFSpriteLayout *layout = nullptr;
3267 SpriteLayoutProcessor processor; // owns heap, borrowed by tmp_layout and t
3268 DrawTileSpriteSpan tmp_layout;
3269 const DrawTileSprites *t = nullptr;
3270 int32_t total_offset;
3271 const RailTypeInfo *rti = nullptr;
3272 uint32_t relocation = 0;
3273 uint32_t ground_relocation = 0;
3274 BaseStation *st = nullptr;
3275 const StationSpec *statspec = nullptr;
3276 uint tile_layout = 0;
3277 auto bridgeable_info = GetStationBridgeableTileInfo(GetStationType(ti->tile));
3278
3279 if (HasStationRail(ti->tile)) {
3280 rti = GetRailTypeInfo(GetRailType(ti->tile));
3281 total_offset = rti->GetRailtypeSpriteOffset();
3282
3283 if (IsCustomStationSpecIndex(ti->tile)) {
3284 /* look for customization */
3285 st = BaseStation::GetByTile(ti->tile);
3286 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3287
3288 if (statspec != nullptr) {
3289 tile_layout = GetStationGfx(ti->tile);
3290
3292 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3293 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + to_underlying(GetRailStationAxis(ti->tile));
3294 }
3295
3296 /* Ensure the chosen tile layout is valid for this custom station */
3297 if (!statspec->renderdata.empty()) {
3298 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3299 if (!layout->NeedsPreprocessing()) {
3300 t = layout;
3301 layout = nullptr;
3302 }
3303 }
3304 }
3305 }
3306 if (statspec != nullptr) bridgeable_info = statspec->bridgeable_info;
3307 } else {
3308 total_offset = 0;
3309 }
3310
3311 StationGfx gfx = GetStationGfx(ti->tile);
3312 if (IsAirport(ti->tile)) {
3313 gfx = GetAirportGfx(ti->tile);
3314 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3315 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3316 if (ats->grf_prop.HasSpriteGroups() && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3317 return;
3318 }
3319 /* No sprite group (or no valid one) found, meaning no graphics associated.
3320 * Use the substitute one instead */
3321 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3322 gfx = ats->grf_prop.subst_id;
3323 }
3324 switch (gfx) {
3325 case APT_RADAR_GRASS_FENCE_SW:
3326 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3327 break;
3328 case APT_GRASS_FENCE_NE_FLAG:
3329 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3330 break;
3331 case APT_RADAR_FENCE_SW:
3332 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3333 break;
3334 case APT_RADAR_FENCE_NE:
3335 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3336 break;
3337 case APT_GRASS_FENCE_NE_FLAG_2:
3338 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3339 break;
3340 }
3341 }
3342
3343 Owner owner = GetTileOwner(ti->tile);
3344
3345 PaletteID palette;
3346 if (Company::IsValidID(owner)) {
3347 palette = GetCompanyPalette(owner);
3348 } else {
3349 /* Some stations are not owner by a company, namely oil rigs */
3350 palette = PALETTE_TO_GREY;
3351 }
3352
3353 if (layout == nullptr && t == nullptr) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3354
3355 /* don't show foundation for docks */
3356 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3357 if (!DrawCustomStationFoundations(statspec, st, ti, tile_layout)) {
3359 }
3360 }
3361
3362 bool draw_ground = false;
3363
3364 if (IsBuoy(ti->tile)) {
3365 DrawWaterClassGround(ti);
3367 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3368 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3369 if (ti->tileh == SLOPE_FLAT) {
3370 DrawWaterClassGround(ti);
3371 } else {
3372 assert(IsDock(ti->tile));
3373 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3374 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WaterClass::Invalid;
3375 if (wc == WaterClass::Sea) {
3376 DrawShoreTile(ti->tileh);
3377 } else {
3378 DrawClearLandTile(ti, 3);
3379 }
3380 }
3381 } else if (IsRoadWaypointTile(ti->tile)) {
3383 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3384 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3385 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3386 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3387 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3388 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3389
3390 if (ti->tileh != SLOPE_FLAT) {
3392 }
3393
3394 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3395 } else {
3396 if (layout != nullptr) {
3397 /* Sprite layout which needs preprocessing */
3398 bool separate_ground = statspec->flags.Test(StationSpecFlag::SeparateGround);
3399 processor = SpriteLayoutProcessor(*layout, total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3400 GetCustomStationRelocation(processor, statspec, st, ti->tile);
3401 tmp_layout = processor.GetLayout();
3402 t = &tmp_layout;
3403 total_offset = 0;
3404 } else if (statspec != nullptr) {
3405 /* Simple sprite layout */
3406 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3408 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3409 }
3410 ground_relocation += rti->fallback_railtype;
3411 }
3412
3413 draw_ground = true;
3414 }
3415
3416 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3417 SpriteID image = t->ground.sprite;
3418 PaletteID pal = t->ground.pal;
3419 RailTrackOffset overlay_offset;
3420 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3422 DrawGroundSprite(image, PAL_NONE);
3423 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3424
3425 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3427 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3428 }
3429 } else {
3430 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3431 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3432 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3433
3434 /* PBS debugging, draw reserved tracks darker */
3435 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3437 }
3438 }
3439 }
3440
3442
3443 if (IsAnyRoadStop(ti->tile)) {
3444 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3445 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3446 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3447 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3448
3449 StationGfx view = GetStationGfx(ti->tile);
3450 StationType type = GetStationType(ti->tile);
3451
3452 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3453 RoadStopDrawModes stop_draw_mode{};
3454 if (stopspec != nullptr) {
3455 stop_draw_mode = stopspec->draw_mode;
3456 st = BaseStation::GetByTile(ti->tile);
3457 std::array<int32_t, 1> regs100;
3458 auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100);
3459 if (result.has_value()) {
3460 if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
3461 stop_draw_mode = static_cast<RoadStopDrawModes>(regs100[0]);
3462 }
3463 if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) {
3464 draw_ground = true;
3465 }
3466 processor = std::move(*result);
3467 tmp_layout = processor.GetLayout();
3468 t = &tmp_layout;
3469 }
3470 }
3471
3472 /* Draw ground sprite */
3473 if (draw_ground) {
3474 SpriteID image = t->ground.sprite;
3475 PaletteID pal = t->ground.pal;
3476 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3477 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3478 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3479 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3480 }
3481 }
3482
3483 if (IsDriveThroughStopTile(ti->tile)) {
3484 if (type != StationType::RoadWaypoint && (stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Overlay))) {
3485 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == Axis::X ? 1 : 0;
3486 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3487 }
3488 } else {
3489 /* Non-drivethrough road stops are only valid for roads. */
3490 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3491
3492 if ((stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Road)) && road_rti->UsesOverlay()) {
3494 DrawGroundSprite(ground + view, PAL_NONE);
3495 }
3496 }
3497 if (stopspec != nullptr) bridgeable_info = stopspec->bridgeable_info;
3498
3499 if (stopspec == nullptr || !stopspec->flags.Test(RoadStopSpecFlag::NoCatenary)) {
3500 /* Draw road, tram catenary */
3501 DrawRoadCatenary(ti);
3502 }
3503 }
3504
3505 if (IsRailWaypoint(ti->tile)) {
3506 /* Don't offset the waypoint graphics; they're always the same. */
3507 total_offset = 0;
3508 }
3509
3510 DrawRailTileSeq(ti, t, TransparencyOption::Buildings, total_offset, relocation, palette);
3511 DrawBridgeMiddle(ti, GetStationBlockedPillars(bridgeable_info, GetStationGfx(ti->tile)));
3512}
3513
3514void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3515{
3516 int32_t total_offset = 0;
3518 const DrawTileSprites *t = GetStationTileLayout(st, image);
3519 const RailTypeInfo *railtype_info = nullptr;
3520
3521 if (railtype != INVALID_RAILTYPE) {
3522 railtype_info = GetRailTypeInfo(railtype);
3523 total_offset = railtype_info->GetRailtypeSpriteOffset();
3524 }
3525
3526 SpriteID img = t->ground.sprite;
3527 RailTrackOffset overlay_offset;
3528 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3530 DrawSprite(img, PAL_NONE, x, y);
3531 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3532 } else {
3533 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3534 }
3535
3536 if (roadtype != INVALID_ROADTYPE) {
3537 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3538 if (image >= 4) {
3539 /* Drive-through stop */
3540 uint sprite_offset = 5 - image;
3541
3542 /* Road underlay takes precedence over tram */
3543 if (roadtype_info->UsesOverlay()) {
3545 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3546
3548 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3549 } else if (RoadTypeIsTram(roadtype)) {
3550 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3551 }
3552 } else {
3553 /* Bay stop */
3554 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3556 DrawSprite(ground + image, PAL_NONE, x, y);
3557 }
3558 }
3559 }
3560
3561 /* Default waypoint has no railtype specific sprites */
3562 DrawRailTileSeqInGUI(x, y, t, (st == StationType::RailWaypoint || st == StationType::RoadWaypoint) ? 0 : total_offset, 0, pal);
3563}
3564
3565
3566static void FillTileDescRoadStop(TileIndex tile, TileDesc &td)
3567{
3568 RoadType road_rt = GetRoadTypeRoad(tile);
3569 RoadType tram_rt = GetRoadTypeTram(tile);
3570 Owner road_owner = INVALID_OWNER;
3571 Owner tram_owner = INVALID_OWNER;
3572 if (road_rt != INVALID_ROADTYPE) {
3573 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3574 td.roadtype = rti->strings.name;
3575 td.road_speed = rti->max_speed / 2;
3576 road_owner = GetRoadOwner(tile, RoadTramType::Road);
3577 }
3578
3579 if (tram_rt != INVALID_ROADTYPE) {
3580 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3581 td.tramtype = rti->strings.name;
3582 td.tram_speed = rti->max_speed / 2;
3583 tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
3584 }
3585
3586 if (IsDriveThroughStopTile(tile)) {
3587 /* Is there a mix of owners? */
3588 if ((tram_owner != INVALID_OWNER && tram_owner != td.owner[0]) ||
3589 (road_owner != INVALID_OWNER && road_owner != td.owner[0])) {
3590 uint i = 1;
3591 if (road_owner != INVALID_OWNER) {
3592 td.owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3593 td.owner[i] = road_owner;
3594 i++;
3595 }
3596 if (tram_owner != INVALID_OWNER) {
3597 td.owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3598 td.owner[i] = tram_owner;
3599 }
3600 }
3601 }
3602}
3603
3604void FillTileDescRailStation(TileIndex tile, TileDesc &td)
3605{
3606 const StationSpec *spec = GetStationSpec(tile);
3607
3608 if (spec != nullptr) {
3610 td.station_name = spec->name;
3611
3612 if (spec->grf_prop.HasGrfFile()) {
3613 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grfid);
3614 td.grf = gc->GetName();
3615 }
3616 }
3617
3618 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3619 td.rail_speed = rti->max_speed;
3620 td.railtype = rti->strings.name;
3621}
3622
3623void FillTileDescAirport(TileIndex tile, TileDesc &td)
3624{
3625 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3627 td.airport_name = as->name;
3628
3629 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3630 td.airport_tile_name = ats->name;
3631
3632 if (as->grf_prop.HasGrfFile()) {
3633 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grfid);
3634 td.grf = gc->GetName();
3635 } else if (ats->grf_prop.HasGrfFile()) {
3636 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grfid);
3637 td.grf = gc->GetName();
3638 }
3639}
3640
3643{
3644 td.owner[0] = GetTileOwner(tile);
3646
3647 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3648 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3649 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3650
3651 StringID str;
3652 switch (GetStationType(tile)) {
3653 default: NOT_REACHED();
3654 case StationType::Rail: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3656 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3657 break;
3658 case StationType::Truck: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3659 case StationType::Bus: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3660 case StationType::Oilrig: {
3661 const Industry *i = Station::GetByTile(tile)->industry;
3662 const IndustrySpec *is = GetIndustrySpec(i->type);
3663 td.owner[0] = i->owner;
3664 str = is->name;
3665 if (is->grf_prop.HasGrfFile()) td.grf = GetGRFConfig(is->grf_prop.grfid)->GetName();
3666 break;
3667 }
3668 case StationType::Dock: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3669 case StationType::Buoy: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3670 case StationType::RailWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3671 case StationType::RoadWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3672 }
3673 td.str = str;
3674}
3675
3676
3679{
3680 TrackBits trackbits{};
3681
3682 switch (mode) {
3684 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3685 trackbits = GetRailStationTrack(tile);
3686 }
3687 break;
3688
3690 /* buoy is coded as a station, it is always on open water */
3691 if (IsBuoy(tile)) {
3692 trackbits = TRACK_BIT_ALL;
3693 /* remove tracks that connect NE map edge */
3694 if (TileX(tile) == 0) trackbits.Reset(TRACK_BIT_3WAY_NE);
3695 /* remove tracks that connect NW map edge */
3696 if (TileY(tile) == 0) trackbits.Reset({Track::Y, Track::Left, Track::Upper});
3697 }
3698 break;
3699
3701 if (IsAnyRoadStop(tile)) {
3702 RoadTramType rtt = (RoadTramType)sub_mode;
3703 if (!HasTileRoadType(tile, rtt)) break;
3704
3705 if (IsBayRoadStopTile(tile)) {
3706 DiagDirection dir = GetBayRoadStopDir(tile);
3707 if (side != DiagDirection::Invalid && dir != side) break;
3708 trackbits = DiagDirToDiagTrack(dir);
3709 } else {
3710 Axis axis = GetDriveThroughStopAxis(tile);
3711 if (side != DiagDirection::Invalid && axis != DiagDirToAxis(side)) break;
3712 trackbits = AxisToTrack(axis);
3713 }
3714 }
3715 break;
3716
3717 default:
3718 break;
3719 }
3720
3721 return {TrackBitsToTrackdirBits(trackbits), {}};
3722}
3723
3724
3727{
3728 auto *st = BaseStation::GetByTile(tile);
3729 switch (GetStationType(tile)) {
3731 TriggerAirportTileAnimation(Station::From(st), tile, AirportAnimationTrigger::TileLoop);
3732 break;
3733
3734 case StationType::Rail:
3736 TriggerStationAnimation(st, tile, StationAnimationTrigger::TileLoop);
3737 break;
3738
3739 case StationType::Dock:
3740 if (!IsTileFlat(tile)) break; // only handle water part
3741 [[fallthrough]];
3742
3743 case StationType::Oilrig: //(station part)
3744 case StationType::Buoy:
3745 TileLoop_Water(tile);
3746 break;
3747
3748 case StationType::Truck:
3749 case StationType::Bus:
3750 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3751 break;
3752
3754 switch (_settings_game.game_creation.landscape) {
3756 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3758 MarkTileDirtyByTile(tile);
3759 }
3760 break;
3761
3765 MarkTileDirtyByTile(tile);
3766 }
3767 break;
3768
3769 default: break;
3770 }
3771
3772 HouseZone new_zone = HouseZone::TownEdge;
3773 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3774 if (t != nullptr) {
3775 new_zone = GetTownRadiusGroup(t, tile);
3776 }
3777
3778 /* Adjust road ground type depending on 'new_zone' */
3780 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3781
3782 if (new_rs != cur_rs) {
3783 SetRoadWaypointRoadside(tile, cur_rs == Roadside::Barren ? new_rs : Roadside::Barren);
3784 MarkTileDirtyByTile(tile);
3785 }
3786
3787 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3788 break;
3789 }
3790
3791 default: break;
3792 }
3793}
3794
3795
3798{
3799 if (HasStationRail(tile)) {
3800 AnimateStationTile(tile);
3801 return;
3802 }
3803
3804 if (IsAirport(tile)) {
3805 AnimateAirportTile(tile);
3806 return;
3807 }
3808
3809 if (IsAnyRoadStopTile(tile)) {
3810 AnimateRoadStopTile(tile);
3811 return;
3812 }
3813}
3814
3815
3818{
3819 const BaseStation *bst = BaseStation::GetByTile(tile);
3820
3823 } else if (IsHangar(tile)) {
3824 const Station *st = Station::From(bst);
3826 } else {
3827 ShowStationViewWindow(bst->index);
3828 }
3829 return true;
3830}
3831
3834{
3835 if (v->type == VehicleType::Train) {
3836 StationID station_id = GetStationIndex(tile);
3837 if (!IsRailStation(tile) || !v->IsMovingFront()) return {};
3838 Vehicle *consist = v->First();
3839 if (!consist->current_order.ShouldStopAtStation(consist, station_id)) return {};
3840
3841 int station_ahead;
3842 int station_length;
3843 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3844
3845 /* Stop whenever that amount of station ahead + the distance from the
3846 * begin of the platform to the stop location is longer than the length
3847 * of the platform. Station ahead 'includes' the current tile where the
3848 * vehicle is on, so we need to subtract that. */
3849 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return {};
3850
3852
3853 x &= 0xF;
3854 y &= 0xF;
3855
3856 if (DiagDirToAxis(dir) != Axis::X) std::swap(x, y);
3857 if (y == TILE_SIZE / 2) {
3858 if (dir != DiagDirection::SE && dir != DiagDirection::SW) x = TILE_SIZE - 1 - x;
3859 stop &= TILE_SIZE - 1;
3860
3861 if (x == stop) {
3862 return VehicleEnterTileState::EnteredStation; // enter station
3863 } else if (x < stop) {
3865 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3866 if (spd < v->cur_speed) v->cur_speed = spd;
3867 }
3868 }
3869 } else if (v->type == VehicleType::Road) {
3871 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir(static_cast<Trackdir>(rv->state)) && rv->frame == 0) {
3872 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3873 /* Attempt to allocate a parking bay in a road stop */
3874 if (RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv)) return {};
3876 }
3877 }
3878 }
3879
3880 return {};
3881}
3882
3888{
3889 /* Collect cargoes accepted since the last big tick. */
3890 CargoTypes cargoes{};
3891 for (CargoType cargo_type : EnumRange(NUM_CARGO)) {
3892 if (st->goods[cargo_type].status.Test(GoodsEntry::State::AcceptedBigtick)) cargoes.Set(cargo_type);
3893 }
3894
3895 /* Anything to do? */
3896 if (cargoes.None()) return;
3897
3898 /* Loop over all houses in the catchment. */
3899 for (TileIndex tile : st->catchment_tiles) {
3900 if (IsTileType(tile, TileType::House)) {
3902 }
3903 }
3904}
3905
3913{
3914 if (!st->IsInUse()) {
3915 if (++st->delete_ctr >= 8) delete st;
3916 return false;
3917 }
3918
3919 if (Station::IsExpected(st)) {
3921
3922 for (GoodsEntry &ge : Station::From(st)->goods) {
3924 }
3925 }
3926
3927
3929
3930 return true;
3931}
3932
3933static inline void byte_inc_sat(uint8_t *p)
3934{
3935 uint8_t b = *p + 1;
3936 if (b != 0) *p = b;
3937}
3938
3945static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3946{
3947 /* If truncating also punish the source stations' ratings to
3948 * decrease the flow of incoming cargo. */
3949
3950 if (!ge->HasData()) return;
3951
3952 StationCargoAmountMap waiting_per_source;
3953 ge->GetData().cargo.Truncate(amount, &waiting_per_source);
3954 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3955 Station *source_station = Station::GetIfValid(i->first);
3956 if (source_station == nullptr) continue;
3957
3958 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3959 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3960 }
3961}
3962
3968{
3969 bool waiting_changed = false;
3970
3971 byte_inc_sat(&st->time_since_load);
3972 byte_inc_sat(&st->time_since_unload);
3973
3974 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3975 GoodsEntry *ge = &st->goods[cs->Index()];
3976
3977 /* The station might not currently be moving this cargo. */
3978 if (!ge->HasRating()) {
3979 /* Slowly increase the rating back to its original level in the case we
3980 * didn't deliver cargo yet to this station. This happens when a bribe
3981 * failed while you didn't moved that cargo yet to a station. */
3982 if (ge->rating < INITIAL_STATION_RATING) ge->rating++;
3983
3984 /* Nothing else to do with this cargo. */
3985 continue;
3986 }
3987
3988 byte_inc_sat(&ge->time_since_pickup);
3989
3990 /* If this cargo hasn't been picked up in a long time, get rid of it. */
3991 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
3993 ge->last_speed = 0;
3994 TruncateCargo(cs, ge);
3995 waiting_changed = true;
3996 continue;
3997 }
3998
3999 bool skip = false;
4000 int rating = 0;
4001 uint waiting = ge->AvailableCount();
4002
4003 /* num_dests is at least 1 if there is any cargo as
4004 * StationID::Invalid() is also a destination.
4005 */
4006 uint num_dests = ge->HasData() ? static_cast<uint>(ge->GetData().cargo.Packets()->MapSize()) : 0;
4007
4008 /* Average amount of cargo per next hop, but prefer solitary stations
4009 * with only one or two next hops. They are allowed to have more
4010 * cargo waiting per next hop.
4011 * With manual cargo distribution waiting_avg = waiting / 2 as then
4012 * StationID::Invalid() is the only destination.
4013 */
4014 uint waiting_avg = waiting / (num_dests + 1);
4015
4016 if (_cheats.station_rating.value) {
4017 ge->rating = rating = MAX_STATION_RATING;
4018 skip = true;
4019 } else if (cs->callback_mask.Test(CargoCallbackMask::StationRatingCalc)) {
4020 /* Perform custom station rating. If it succeeds the speed, days in transit and
4021 * waiting cargo ratings must not be executed. */
4022
4023 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
4024 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
4025
4026 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
4028 | (ClampTo<uint8_t>(last_speed) << 24);
4029 /* Convert to the 'old' vehicle types */
4030 uint32_t var10 = (st->last_vehicle_type == VehicleType::Invalid) ? 0x0 : (to_underlying(st->last_vehicle_type) + 0x10);
4031 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
4032 if (callback != CALLBACK_FAILED) {
4033 skip = true;
4034 rating = GB(callback, 0, 14);
4035
4036 /* Simulate a 15 bit signed value */
4037 if (HasBit(callback, 14)) rating -= 0x4000;
4038 }
4039 }
4040
4041 if (!skip) {
4042 int b = ge->last_speed - 85;
4043 if (b >= 0) rating += b >> 2;
4044
4045 uint8_t waittime = ge->time_since_pickup;
4046 if (st->last_vehicle_type == VehicleType::Ship) waittime >>= 2;
4047 if (waittime <= 21) rating += 25;
4048 if (waittime <= 12) rating += 25;
4049 if (waittime <= 6) rating += 45;
4050 if (waittime <= 3) rating += 35;
4051
4052 rating -= 90;
4053 if (ge->max_waiting_cargo <= 1500) rating += 55;
4054 if (ge->max_waiting_cargo <= 1000) rating += 35;
4055 if (ge->max_waiting_cargo <= 600) rating += 10;
4056 if (ge->max_waiting_cargo <= 300) rating += 20;
4057 if (ge->max_waiting_cargo <= 100) rating += 10;
4058 }
4059
4060 if (Company::IsValidID(st->owner) && st->town->statues.Test(st->owner)) rating += 26;
4061
4062 uint8_t age = ge->last_age;
4063 if (age < 3) rating += 10;
4064 if (age < 2) rating += 10;
4065 if (age < 1) rating += 13;
4066
4067 {
4068 int or_ = ge->rating; // old rating
4069
4070 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
4071 ge->rating = rating = ClampTo<uint8_t>(or_ + Clamp(rating - or_, -2, 2));
4072
4073 /* if rating is <= 64 and more than 100 items waiting on average per destination,
4074 * remove some random amount of goods from the station */
4075 if (rating <= 64 && waiting_avg >= 100) {
4076 int dec = Random() & 0x1F;
4077 if (waiting_avg < 200) dec &= 7;
4078 waiting -= (dec + 1) * num_dests;
4079 waiting_changed = true;
4080 }
4081
4082 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
4083 if (rating <= 127 && waiting != 0) {
4084 uint32_t r = Random();
4085 if (rating <= (int)GB(r, 0, 7)) {
4086 /* Need to have int, otherwise it will just overflow etc. */
4087 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) + 1) * num_dests), 0);
4088 waiting_changed = true;
4089 }
4090 }
4091
4092 /* At some point we really must cap the cargo. Previously this
4093 * was a strict 4095, but now we'll have a less strict, but
4094 * increasingly aggressive truncation of the amount of cargo. */
4095 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
4096 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
4097 static const uint MAX_WAITING_CARGO = 1 << 15;
4098
4099 if (waiting > WAITING_CARGO_THRESHOLD) {
4100 uint difference = waiting - WAITING_CARGO_THRESHOLD;
4101 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
4102
4103 waiting = std::min(waiting, MAX_WAITING_CARGO);
4104 waiting_changed = true;
4105 }
4106
4107 /* We can't truncate cargo that's already reserved for loading.
4108 * Thus StoredCount() here. */
4109 if (waiting_changed && waiting < ge->AvailableCount()) {
4110 /* Feed back the exact own waiting cargo at this station for the
4111 * next rating calculation. */
4112 ge->max_waiting_cargo = 0;
4113
4114 TruncateCargo(cs, ge, ge->AvailableCount() - waiting);
4115 } else {
4116 /* If the average number per next hop is low, be more forgiving. */
4117 ge->max_waiting_cargo = waiting_avg;
4118 }
4119 }
4120 }
4121
4122 StationID index = st->index;
4123 if (waiting_changed) {
4124 SetWindowDirty(WindowClass::StationView, index); // update whole window
4125 } else {
4126 SetWindowWidgetDirty(WindowClass::StationView, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4127 }
4128}
4129
4138void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
4139{
4140 GoodsEntry &ge = st->goods[cargo];
4141
4142 /* Reroute cargo in station. */
4143 if (ge.HasData()) ge.GetData().cargo.Reroute(UINT_MAX, &ge.GetData().cargo, avoid, avoid2, &ge);
4144
4145 /* Reroute cargo staged to be transferred. */
4146 for (Vehicle *v : st->loading_vehicles) {
4147 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4148 if (u->cargo_type != cargo) continue;
4149 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4150 }
4151 }
4152}
4153
4163{
4164 for (CargoType cargo : EnumRange(NUM_CARGO)) {
4165 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual);
4166 GoodsEntry &ge = from->goods[cargo];
4168 if (lg == nullptr) continue;
4169 std::vector<NodeID> to_remove{};
4170 for (Edge &edge : (*lg)[ge.node].edges) {
4171 Station *to = Station::Get((*lg)[edge.dest_node].station);
4172 assert(to->goods[cargo].node == edge.dest_node);
4173 assert(TimerGameEconomy::date >= edge.LastUpdate());
4175 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4176 bool updated = false;
4177
4178 if (auto_distributed) {
4179 /* Have all vehicles refresh their next hops before deciding to
4180 * remove the node. */
4181 std::vector<Vehicle *> vehicles;
4182 for (const OrderList *l : OrderList::Iterate()) {
4183 bool found_from = false;
4184 bool found_to = false;
4185 for (const Order &order : l->GetOrders()) {
4186 if (!order.IsType(OT_GOTO_STATION) && !order.IsType(OT_IMPLICIT)) continue;
4187 if (order.GetDestination() == from->index) {
4188 found_from = true;
4189 if (found_to) break;
4190 } else if (order.GetDestination() == to->index) {
4191 found_to = true;
4192 if (found_from) break;
4193 }
4194 }
4195 if (!found_to || !found_from) continue;
4196 vehicles.push_back(l->GetFirstSharedVehicle());
4197 }
4198
4199 auto iter = vehicles.begin();
4200 while (iter != vehicles.end()) {
4201 Vehicle *v = *iter;
4202 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4204 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4205 }
4206 if (edge.LastUpdate() == TimerGameEconomy::date) {
4207 updated = true;
4208 break;
4209 }
4210
4211 Vehicle *next_shared = v->NextShared();
4212 if (next_shared) {
4213 *iter = next_shared;
4214 ++iter;
4215 } else {
4216 iter = vehicles.erase(iter);
4217 }
4218
4219 if (iter == vehicles.end()) iter = vehicles.begin();
4220 }
4221 }
4222
4223 if (!updated) {
4224 /* If it's still considered dead remove it. */
4225 to_remove.emplace_back(to->goods[cargo].node);
4226 if (ge.HasData()) ge.GetData().flows.DeleteFlows(to->index);
4227 RerouteCargo(from, cargo, to->index, from->index);
4228 }
4229 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4230 edge.Restrict();
4231 if (ge.HasData()) ge.GetData().flows.RestrictFlows(to->index);
4232 RerouteCargo(from, cargo, to->index, from->index);
4233 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4234 edge.Release();
4235 }
4236 }
4237 /* Remove dead edges. */
4238 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4239
4240 assert(TimerGameEconomy::date >= lg->LastCompression());
4242 lg->Compress();
4243 }
4244 }
4245}
4246
4257void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
4258{
4259 GoodsEntry &ge1 = st->goods[cargo];
4260 Station *st2 = Station::Get(next_station_id);
4261 GoodsEntry &ge2 = st2->goods[cargo];
4262 LinkGraph *lg = nullptr;
4263 if (ge1.link_graph == LinkGraphID::Invalid()) {
4264 if (ge2.link_graph == LinkGraphID::Invalid()) {
4266 lg = LinkGraph::Create(cargo);
4268 ge2.link_graph = lg->index;
4269 ge2.node = lg->AddNode(st2);
4270 } else {
4271 Debug(Facility::Misc, Severity::Critical, "Can't allocate link graph");
4272 }
4273 } else {
4274 lg = LinkGraph::Get(ge2.link_graph);
4275 }
4276 if (lg) {
4277 ge1.link_graph = lg->index;
4278 ge1.node = lg->AddNode(st);
4279 }
4280 } else if (ge2.link_graph == LinkGraphID::Invalid()) {
4281 lg = LinkGraph::Get(ge1.link_graph);
4282 ge2.link_graph = lg->index;
4283 ge2.node = lg->AddNode(st2);
4284 } else {
4285 lg = LinkGraph::Get(ge1.link_graph);
4286 if (ge1.link_graph != ge2.link_graph) {
4288 if (lg->Size() < lg2->Size()) {
4289 LinkGraphSchedule::instance.Dequeue(lg);
4290 lg2->Merge(lg); // Updates GoodsEntries of lg
4291 lg = lg2;
4292 } else {
4293 LinkGraphSchedule::instance.Dequeue(lg2);
4294 lg->Merge(lg2); // Updates GoodsEntries of lg2
4295 }
4296 }
4297 }
4298 if (lg != nullptr) {
4299 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, modes);
4300 }
4301}
4302
4310void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4311{
4312 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4313 if (v->refit_cap > 0) {
4314 /* The cargo count can indeed be higher than the refit_cap if
4315 * wagons have been auto-replaced and subsequently auto-
4316 * refitted to a higher capacity. The cargo gets redistributed
4317 * among the wagons in that case.
4318 * As usage is not such an important figure anyway we just
4319 * ignore the additional cargo then.*/
4320 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4321 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EdgeUpdateMode::Increase);
4322 }
4323 }
4324}
4325
4326/* called for every station each tick */
4327static void StationHandleSmallTick(BaseStation *st)
4328{
4329 if (st->facilities.Test(StationFacility::Waypoint) || !st->IsInUse()) return;
4330
4331 uint8_t b = st->delete_ctr + 1;
4332 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4333 st->delete_ctr = b;
4334
4335 if (b == 0) UpdateStationRating(Station::From(st));
4336}
4337
4338void OnTick_Station()
4339{
4340 if (_game_mode == GameMode::Editor) return;
4341
4342 for (BaseStation *st : BaseStation::Iterate()) {
4343 StationHandleSmallTick(st);
4344
4345 /* Clean up the link graph about once a week. */
4348 };
4349
4350 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4352 /* Stop processing this station if it was deleted */
4353 if (!StationHandleBigTick(st)) continue;
4354 }
4355
4356 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4358 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4359 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4360 if (Station::IsExpected(st)) TriggerAirportAnimation(Station::From(st), AirportAnimationTrigger::AcceptanceTick);
4361 }
4362 }
4363}
4364
4366static const IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Station}, [](auto)
4367{
4368 for (Station *st : Station::Iterate()) {
4369 for (GoodsEntry &ge : st->goods) {
4372 }
4373 }
4374});
4375
4384void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4385{
4386 ForAllStationsRadius(tile, radius, [&](Station *st) {
4387 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4388 for (GoodsEntry &ge : st->goods) {
4389 if (ge.status.Any()) {
4390 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4391 }
4392 }
4393 }
4394 });
4395}
4396
4397static uint UpdateStationWaiting(Station *st, CargoType cargo, uint amount, Source source)
4398{
4399 /* We can't allocate a CargoPacket? Then don't do anything
4400 * at all; i.e. just discard the incoming cargo. */
4401 if (!CargoPacket::CanAllocateItem()) return 0;
4402
4403 GoodsEntry &ge = st->goods[cargo];
4404 amount += ge.amount_fract;
4405 ge.amount_fract = GB(amount, 0, 8);
4406
4407 amount >>= 8;
4408 /* No new "real" cargo item yet. */
4409 if (amount == 0) return 0;
4410
4411 StationID next = ge.GetVia(st->index);
4412 ge.GetOrCreateData().cargo.Append(CargoPacket::Create(st->index, amount, source), next);
4413 LinkGraph *lg = nullptr;
4414 if (ge.link_graph == LinkGraphID::Invalid()) {
4415 if (LinkGraph::CanAllocateItem()) {
4416 lg = LinkGraph::Create(cargo);
4418 ge.link_graph = lg->index;
4419 ge.node = lg->AddNode(st);
4420 } else {
4421 Debug(Facility::Misc, Severity::Critical, "Can't allocate link graph");
4422 }
4423 } else {
4424 lg = LinkGraph::Get(ge.link_graph);
4425 }
4426 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4427
4428 if (!ge.HasRating()) {
4429 InvalidateWindowData(WindowClass::StationList, st->owner);
4431 }
4432
4434 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4435 TriggerAirportAnimation(st, AirportAnimationTrigger::NewCargo, cargo);
4437 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4438
4439
4440 SetWindowDirty(WindowClass::StationView, st->index);
4441 st->MarkTilesDirty(true);
4442 return amount;
4443}
4444
4445static bool IsUniqueStationName(const std::string &name)
4446{
4447 for (const Station *st : Station::Iterate()) {
4448 if (!st->name.empty() && st->name == name) return false;
4449 }
4450
4451 return true;
4452}
4453
4461CommandCost CmdRenameStation(DoCommandFlags flags, StationID station_id, const std::string &text)
4462{
4463 Station *st = Station::GetIfValid(station_id);
4464 if (st == nullptr) return CMD_ERROR;
4465
4466 CommandCost ret = CheckOwnership(st->owner);
4467 if (ret.Failed()) return ret;
4468
4469 bool reset = text.empty();
4470
4471 if (!reset) {
4473 if (!IsUniqueStationName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
4474 }
4475
4476 if (flags.Test(DoCommandFlag::Execute)) {
4477 st->cached_name.clear();
4478 if (reset) {
4479 st->name.clear();
4480 } else {
4481 st->name = text;
4482 }
4483
4484 st->UpdateVirtCoord();
4485 InvalidateWindowData(WindowClass::StationList, st->owner, 1);
4486 }
4487
4488 return CommandCost();
4489}
4490
4498std::tuple<CommandCost, StationID> CmdMoveStationName(DoCommandFlags flags, StationID station_id, TileIndex tile)
4499{
4500 Station *st = Station::GetIfValid(station_id);
4501 if (st == nullptr) return { CMD_ERROR, StationID::Invalid() };
4502
4503 if (st->owner != OWNER_NONE) {
4504 CommandCost ret = CheckOwnership(st->owner);
4505 if (ret.Failed()) return { ret, StationID::Invalid() };
4506 }
4507
4508 if (!st->spread.Contains(tile)) {
4509 return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4510 }
4511
4512 bool other_station = false;
4513 /* Check if the tile is the base tile of another station */
4514 ForAllStationsRadius(tile, 0, [&](BaseStation *s) {
4515 if (s != nullptr) {
4516 if (s != st && s->xy == tile) other_station = true;
4517 }
4518 });
4519 if (other_station) return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4520
4521 if (flags.Test(DoCommandFlag::Execute)) {
4522 st->MoveSign(tile);
4523
4524 st->UpdateVirtCoord();
4525 st->RecomputeCatchment();
4526 }
4527 return { CommandCost(), station_id };
4528}
4529
4535void CcMoveStationName(Commands, const CommandCost &result, StationID station_id)
4536 {
4537 if (result.Failed()) return;
4538
4540 Station *st = Station::Get(station_id);
4541 SetViewportStationRect(st, false);
4542 }
4543
4544static void AddNearbyStationsByCatchment(TileIndex tile, StationList &stations, StationList &nearby)
4545{
4546 for (Station *st : nearby) {
4547 if (st->TileIsInCatchment(tile)) stations.insert(st);
4548 }
4549}
4550
4556{
4557 if (this->tile != INVALID_TILE) {
4558 if (IsTileType(this->tile, TileType::House)) {
4559 /* Town nearby stations need to be filtered per tile. */
4560 assert(this->w == 1 && this->h == 1);
4561 AddNearbyStationsByCatchment(this->tile, this->stations, Town::GetByTile(this->tile)->stations_near);
4562 } else {
4563 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4564 this->stations.insert(st);
4565 return true;
4566 });
4567 }
4568 this->tile = INVALID_TILE;
4569 }
4570 return this->stations;
4571}
4572
4573
4574static bool CanMoveGoodsToStation(const Station *st, CargoType cargo)
4575{
4576 /* Is the station reserved exclusively for somebody else? */
4577 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4578
4579 /* Lowest possible rating, better not to give cargo anymore. */
4580 if (st->goods[cargo].rating == 0) return false;
4581
4582 /* Selectively servicing stations, and not this one. */
4583 if (_settings_game.order.selectgoods && !st->goods[cargo].HasVehicleEverTriedLoading()) return false;
4584
4586 /* Passengers are never served by just a truck stop. */
4587 if (st->facilities == StationFacility::TruckStop) return false;
4588 } else {
4589 /* Non-passengers are never served by just a bus stop. */
4590 if (st->facilities == StationFacility::BusStop) return false;
4591 }
4592 return true;
4593}
4594
4595uint MoveGoodsToStation(CargoType cargo, uint amount, Source source, const StationList &all_stations, Owner exclusivity)
4596{
4597 /* Return if nothing to do. Also the rounding below fails for 0. */
4598 if (all_stations.empty()) return 0;
4599 if (amount == 0) return 0;
4600
4601 Station *first_station = nullptr;
4602 typedef std::pair<Station *, uint> StationInfo;
4603 std::vector<StationInfo> used_stations;
4604
4605 for (Station *st : all_stations) {
4606 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4607 if (!CanMoveGoodsToStation(st, cargo)) continue;
4608
4609 /* Avoid allocating a vector if there is only one station to significantly
4610 * improve performance in this common case. */
4611 if (first_station == nullptr) {
4612 first_station = st;
4613 continue;
4614 }
4615 if (used_stations.empty()) {
4616 used_stations.reserve(2);
4617 used_stations.emplace_back(first_station, 0);
4618 }
4619 used_stations.emplace_back(st, 0);
4620 }
4621
4622 /* no stations around at all? */
4623 if (first_station == nullptr) return 0;
4624
4625 if (used_stations.empty()) {
4626 /* only one station around */
4627 amount *= first_station->goods[cargo].rating + 1;
4628 return UpdateStationWaiting(first_station, cargo, amount, source);
4629 }
4630
4631 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_best = {}; // best rating for each company, including OWNER_NONE
4632 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_sum = {}; // sum of ratings for each company
4633 uint best_rating = 0;
4634 uint best_sum = 0; // sum of best ratings for each company
4635
4636 for (auto &p : used_stations) {
4637 auto owner = p.first->owner;
4638 auto rating = p.first->goods[cargo].rating;
4639 if (rating > company_best[owner]) {
4640 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4641 company_best[owner] = rating;
4642 if (rating > best_rating) best_rating = rating;
4643 }
4644 company_sum[owner] += rating;
4645 }
4646
4647 /* From now we'll calculate with fractional cargo amounts.
4648 * First determine how much cargo we really have. */
4649 amount *= best_rating + 1;
4650
4651 uint moving = 0;
4652 for (auto &p : used_stations) {
4653 Owner owner = p.first->owner;
4654 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4655 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4656 p.second = amount * company_best[owner] * p.first->goods[cargo].rating / best_sum / company_sum[owner];
4657 moving += p.second;
4658 }
4659
4660 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4661 if (amount > moving) {
4662 std::stable_sort(used_stations.begin(), used_stations.end(), [cargo](const StationInfo &a, const StationInfo &b) {
4663 return b.first->goods[cargo].rating < a.first->goods[cargo].rating;
4664 });
4665
4666 assert(amount - moving <= used_stations.size());
4667 for (uint i = 0; i < amount - moving; i++) {
4668 used_stations[i].second++;
4669 }
4670 }
4671
4672 uint moved = 0;
4673 for (auto &p : used_stations) {
4674 moved += UpdateStationWaiting(p.first, cargo, p.second, source);
4675 }
4676
4677 return moved;
4678}
4679
4680void UpdateStationDockingTiles(Station *st)
4681{
4682 st->docking_station.Clear();
4683
4684 /* For neutral stations, start with the industry area instead of dock area */
4685 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4686
4687 if (area->tile == INVALID_TILE) return;
4688
4689 int x = TileX(area->tile);
4690 int y = TileY(area->tile);
4691
4692 /* Expand the area by a tile on each side while
4693 * making sure that we remain inside the map. */
4694 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4695 int x1 = std::max<int>(x - 1, 0);
4696
4697 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4698 int y1 = std::max<int>(y - 1, 0);
4699
4700 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4701 for (TileIndex tile : ta) {
4702 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4703 }
4704}
4705
4706void BuildOilRig(TileIndex tile)
4707{
4708 if (!Station::CanAllocateItem()) {
4709 Debug(Facility::Misc, Severity::Critical, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4710 return;
4711 }
4712
4713 Station *st = Station::Create(tile);
4714 _station_kdtree.Insert(st->index);
4715 st->town = ClosestTownFromTile(tile, UINT_MAX);
4716
4718
4719 assert(IsTileType(tile, TileType::Industry));
4720 /* Mark industry as associated both ways */
4721 st->industry = Industry::GetByTile(tile);
4722 st->industry->neutral_station = st;
4723 DeleteAnimatedTile(tile);
4724 MakeOilrig(tile, st->index, GetWaterClass(tile));
4725
4726 st->owner = OWNER_NONE;
4727 st->airport.type = AT_OILRIG;
4729 st->airport.Add(tile);
4730 st->ship_station.Add(tile);
4733 UpdateStationDockingTiles(st);
4734
4735 st->spread.Add(tile);
4736
4737 st->UpdateVirtCoord();
4738
4739 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4740 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4741 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4743 StationList nearby = std::move(st->industry->stations_near);
4744 st->industry->stations_near.clear();
4745 for (Station *near : nearby) {
4746 near->RecomputeCatchment(true);
4747 UpdateStationAcceptance(near, true);
4748 }
4749 }
4750
4751 st->RecomputeCatchment();
4752 UpdateStationAcceptance(st, false);
4753}
4754
4755void DeleteOilRig(TileIndex tile)
4756{
4757 Station *st = Station::GetByTile(tile);
4758
4759 MakeWaterKeepingClass(tile, OWNER_NONE);
4760
4761 /* The oil rig station is not supposed to be shared with anything else */
4762 [[maybe_unused]] static constexpr StationFacilities expected_facility{StationFacility::Airport, StationFacility::Dock};
4763 assert(st->facilities == expected_facility && st->airport.type == AT_OILRIG);
4764 if (st->industry != nullptr && st->industry->neutral_station == st) {
4765 /* Don't leave dangling neutral station pointer */
4766 st->industry->neutral_station = nullptr;
4767 }
4768 delete st;
4769}
4770
4772static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4773{
4774 if (IsAnyRoadStopTile(tile)) {
4775 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
4776 /* Update all roadtypes, no matter if they are present */
4777 if (GetRoadOwner(tile, rtt) == old_owner) {
4778 RoadType rt = GetRoadType(tile, rtt);
4779 if (rt != INVALID_ROADTYPE) {
4780 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4781 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4782 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4783 }
4784 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4785 }
4786 }
4787 }
4788
4789 if (!IsTileOwner(tile, old_owner)) return;
4790
4791 if (new_owner != INVALID_OWNER) {
4792 /* Update company infrastructure counts. Only do it here
4793 * if the new owner is valid as otherwise the clear
4794 * command will do it for us. No need to dirty windows
4795 * here, we'll redraw the whole screen anyway.*/
4796 Company *old_company = Company::Get(old_owner);
4797 Company *new_company = Company::Get(new_owner);
4798
4799 /* Update counts for underlying infrastructure. */
4800 switch (GetStationType(tile)) {
4801 case StationType::Rail:
4803 if (!IsStationTileBlocked(tile)) {
4804 old_company->infrastructure.rail[GetRailType(tile)]--;
4805 new_company->infrastructure.rail[GetRailType(tile)]++;
4806 }
4807 break;
4808
4809 case StationType::Bus:
4810 case StationType::Truck:
4812 /* Road stops were already handled above. */
4813 break;
4814
4815 case StationType::Buoy:
4816 case StationType::Dock:
4817 if (GetWaterClass(tile) == WaterClass::Canal) {
4818 old_company->infrastructure.water--;
4819 new_company->infrastructure.water++;
4820 }
4821 break;
4822
4823 default:
4824 break;
4825 }
4826
4827 /* Update station tile count. */
4828 if (!IsBuoy(tile) && !IsAirport(tile)) {
4829 old_company->infrastructure.station--;
4830 new_company->infrastructure.station++;
4831 }
4832
4833 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4834 SetTileOwner(tile, new_owner);
4835 InvalidateWindowClassesData(WindowClass::StationList, 0);
4836 } else {
4837 if (IsDriveThroughStopTile(tile)) {
4838 /* Remove the drive-through road stop */
4839 if (IsRoadWaypoint(tile)) {
4840 Command<Commands::RemoveFromRoadWaypoint>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, tile);
4841 } else {
4842 Command<Commands::RemoveRoadStop>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, 1, 1, (GetStationType(tile) == StationType::Truck) ? RoadStopType::Truck : RoadStopType::Bus, false);
4843 }
4844 assert(IsTileType(tile, TileType::Road));
4845 /* Change owner of tile and all roadtypes */
4846 ChangeTileOwner(tile, old_owner, new_owner);
4847 } else {
4848 Command<Commands::LandscapeClear>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile);
4849 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4850 * Update owner of buoy if it was not removed (was in orders).
4851 * Do not update when owned by OWNER_WATER (sea and rivers). */
4852 if ((IsTileType(tile, TileType::Water) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4853 }
4854 }
4855}
4856
4866{
4867 /* Water flooding can always clear road stops. */
4868 if (_current_company == OWNER_WATER) return CommandCost();
4869
4870 CommandCost ret;
4871
4872 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4873 Owner tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
4874 if (tram_owner != OWNER_NONE) {
4875 ret = CheckOwnership(tram_owner);
4876 if (ret.Failed()) return ret;
4877 }
4878 }
4879
4880 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4881 Owner road_owner = GetRoadOwner(tile, RoadTramType::Road);
4882 if (road_owner == OWNER_TOWN) {
4884 if (ret.Failed()) return ret;
4885 } else if (road_owner != OWNER_NONE) {
4886 ret = CheckOwnership(road_owner);
4887 if (ret.Failed()) return ret;
4888 }
4889 }
4890
4891 return CommandCost();
4892}
4893
4896{
4897 if (flags.Test(DoCommandFlag::Auto)) {
4898 switch (GetStationType(tile)) {
4899 default: break;
4900 case StationType::Rail: return CommandCost(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4901 case StationType::RailWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4902 case StationType::Airport: return CommandCost(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4903 case StationType::Truck: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4904 case StationType::Bus: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4905 case StationType::RoadWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4906 case StationType::Buoy: return CommandCost(STR_ERROR_BUOY_IN_THE_WAY);
4907 case StationType::Dock: return CommandCost(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4909 return CommandCostWithParam(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY, STR_INDUSTRY_NAME_OIL_RIG);
4910 }
4911 }
4912
4913 switch (GetStationType(tile)) {
4914 case StationType::Rail: return RemoveRailStation(tile, flags);
4915 case StationType::RailWaypoint: return RemoveRailWaypoint(tile, flags);
4916 case StationType::Airport: return RemoveAirport(tile, flags);
4917 case StationType::Truck: [[fallthrough]];
4918 case StationType::Bus:
4919 if (IsDriveThroughStopTile(tile)) {
4920 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4921 if (remove_road.Failed()) return remove_road;
4922 }
4923 return RemoveRoadStop(tile, flags);
4925 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4926 if (remove_road.Failed()) return remove_road;
4927 return RemoveRoadWaypointStop(tile, flags);
4928 }
4929 case StationType::Buoy: return RemoveBuoy(tile, flags);
4930 case StationType::Dock: return RemoveDock(tile, flags);
4931 default: break;
4932 }
4933
4934 return CMD_ERROR;
4935}
4936
4938static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
4939{
4940 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4941 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4942 * TTDP does not call it.
4943 */
4944 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4945 switch (GetStationType(tile)) {
4947 case StationType::Rail: {
4948 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
4950 }
4951
4954
4955 case StationType::Truck:
4956 case StationType::Bus:
4958 if (IsDriveThroughStopTile(tile)) {
4959 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
4960 } else {
4961 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
4962 }
4964 }
4965
4966 default: break;
4967 }
4968 }
4969 }
4970 return Command<Commands::LandscapeClear>::Do(flags, tile);
4971}
4972
4978uint FlowStat::GetShare(StationID st) const
4979{
4980 uint32_t prev = 0;
4981 for (const auto &it : this->shares) {
4982 if (it.second == st) {
4983 return it.first - prev;
4984 } else {
4985 prev = it.first;
4986 }
4987 }
4988 return 0;
4989}
4990
4997StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
4998{
4999 if (this->unrestricted == 0) return StationID::Invalid();
5000 assert(!this->shares.empty());
5001 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
5002 assert(it != this->shares.end() && it->first <= this->unrestricted);
5003 if (it->second != excluded && it->second != excluded2) return it->second;
5004
5005 /* We've hit one of the excluded stations.
5006 * Draw another share, from outside its range. */
5007
5008 uint end = it->first;
5009 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
5010 uint interval = end - begin;
5011 if (interval >= this->unrestricted) return StationID::Invalid(); // Only one station in the map.
5012 uint new_max = this->unrestricted - interval;
5013 uint rand = RandomRange(new_max);
5014 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
5015 this->shares.upper_bound(rand + interval);
5016 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
5017 if (it2->second != excluded && it2->second != excluded2) return it2->second;
5018
5019 /* We've hit the second excluded station.
5020 * Same as before, only a bit more complicated. */
5021
5022 uint end2 = it2->first;
5023 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
5024 uint interval2 = end2 - begin2;
5025 if (interval2 >= new_max) return StationID::Invalid(); // Only the two excluded stations in the map.
5026 new_max -= interval2;
5027 if (begin > begin2) {
5028 std::swap(begin, begin2);
5029 std::swap(end, end2);
5030 std::swap(interval, interval2);
5031 }
5032 rand = RandomRange(new_max);
5033 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
5034 if (rand < begin) {
5035 it3 = this->shares.upper_bound(rand);
5036 } else if (rand < begin2 - interval) {
5037 it3 = this->shares.upper_bound(rand + interval);
5038 } else {
5039 it3 = this->shares.upper_bound(rand + interval + interval2);
5040 }
5041 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
5042 return it3->second;
5043}
5044
5051{
5052 assert(!this->shares.empty());
5053 SharesMap new_shares;
5054 uint i = 0;
5055 for (const auto &it : this->shares) {
5056 new_shares[++i] = it.second;
5057 if (it.first == this->unrestricted) this->unrestricted = i;
5058 }
5059 this->shares.swap(new_shares);
5060 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
5061}
5062
5069void FlowStat::ChangeShare(StationID st, int flow)
5070{
5071 /* We assert only before changing as afterwards the shares can actually
5072 * be empty. In that case the whole flow stat must be deleted then. */
5073 assert(!this->shares.empty());
5074
5075 uint removed_shares = 0;
5076 uint added_shares = 0;
5077 uint last_share = 0;
5078 SharesMap new_shares;
5079 for (const auto &it : this->shares) {
5080 if (it.second == st) {
5081 if (flow < 0) {
5082 uint share = it.first - last_share;
5083 if (flow == INT_MIN || (uint)(-flow) >= share) {
5084 removed_shares += share;
5085 if (it.first <= this->unrestricted) this->unrestricted -= share;
5086 if (flow != INT_MIN) flow += share;
5087 last_share = it.first;
5088 continue; // remove the whole share
5089 }
5090 removed_shares += (uint)(-flow);
5091 } else {
5092 added_shares += (uint)(flow);
5093 }
5094 if (it.first <= this->unrestricted) this->unrestricted += flow;
5095
5096 /* If we don't continue above the whole flow has been added or
5097 * removed. */
5098 flow = 0;
5099 }
5100 new_shares[it.first + added_shares - removed_shares] = it.second;
5101 last_share = it.first;
5102 }
5103 if (flow > 0) {
5104 new_shares[last_share + (uint)flow] = st;
5105 if (this->unrestricted < last_share) {
5106 this->ReleaseShare(st);
5107 } else {
5108 this->unrestricted += flow;
5109 }
5110 }
5111 this->shares.swap(new_shares);
5112}
5113
5119void FlowStat::RestrictShare(StationID st)
5120{
5121 assert(!this->shares.empty());
5122 uint flow = 0;
5123 uint last_share = 0;
5124 SharesMap new_shares;
5125 for (auto &it : this->shares) {
5126 if (flow == 0) {
5127 if (it.first > this->unrestricted) return; // Not present or already restricted.
5128 if (it.second == st) {
5129 flow = it.first - last_share;
5130 this->unrestricted -= flow;
5131 } else {
5132 new_shares[it.first] = it.second;
5133 }
5134 } else {
5135 new_shares[it.first - flow] = it.second;
5136 }
5137 last_share = it.first;
5138 }
5139 if (flow == 0) return;
5140 new_shares[last_share + flow] = st;
5141 this->shares.swap(new_shares);
5142 assert(!this->shares.empty());
5143}
5144
5150void FlowStat::ReleaseShare(StationID st)
5151{
5152 assert(!this->shares.empty());
5153 uint flow = 0;
5154 uint next_share = 0;
5155 bool found = false;
5156 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
5157 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
5158 if (found) {
5159 flow = next_share - it->first;
5160 this->unrestricted += flow;
5161 break;
5162 } else {
5163 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
5164 if (it->second == st) found = true;
5165 }
5166 next_share = it->first;
5167 }
5168 if (flow == 0) return;
5169 SharesMap new_shares;
5170 new_shares[flow] = st;
5171 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
5172 if (it->second != st) {
5173 new_shares[flow + it->first] = it->second;
5174 } else {
5175 flow = 0;
5176 }
5177 }
5178 this->shares.swap(new_shares);
5179 assert(!this->shares.empty());
5180}
5181
5188{
5189 assert(runtime > 0);
5190 SharesMap new_shares;
5191 uint share = 0;
5192 for (auto i : this->shares) {
5193 share = std::max(share + 1, i.first * 30 / runtime);
5194 new_shares[share] = i.second;
5195 if (this->unrestricted == i.first) this->unrestricted = share;
5196 }
5197 this->shares.swap(new_shares);
5198}
5199
5206void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5207{
5208 FlowStatMap::iterator origin_it = this->find(origin);
5209 if (origin_it == this->end()) {
5210 this->emplace(origin, FlowStat(via, flow));
5211 } else {
5212 origin_it->second.ChangeShare(via, flow);
5213 assert(!origin_it->second.GetShares()->empty());
5214 }
5215}
5216
5225void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5226{
5227 FlowStatMap::iterator prev_it = this->find(origin);
5228 if (prev_it == this->end()) {
5229 FlowStat fs(via, flow);
5230 fs.AppendShare(StationID::Invalid(), flow);
5231 this->emplace(origin, fs);
5232 } else {
5233 prev_it->second.ChangeShare(via, flow);
5234 prev_it->second.ChangeShare(StationID::Invalid(), flow);
5235 assert(!prev_it->second.GetShares()->empty());
5236 }
5237}
5238
5244{
5245 for (auto &i : *this) {
5246 FlowStat &fs = i.second;
5247 uint local = fs.GetShare(StationID::Invalid());
5248 if (local > INT_MAX) { // make sure it fits in an int
5249 fs.ChangeShare(self, -INT_MAX);
5250 fs.ChangeShare(StationID::Invalid(), -INT_MAX);
5251 local -= INT_MAX;
5252 }
5253 fs.ChangeShare(self, -(int)local);
5254 fs.ChangeShare(StationID::Invalid(), -(int)local);
5255
5256 /* If the local share is used up there must be a share for some
5257 * remote station. */
5258 assert(!fs.GetShares()->empty());
5259 }
5260}
5261
5268std::vector<StationID> FlowStatMap::DeleteFlows(StationID via)
5269{
5270 std::vector<StationID> ret;
5271 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5272 FlowStat &s_flows = f_it->second;
5273 s_flows.ChangeShare(via, INT_MIN);
5274 if (s_flows.GetShares()->empty()) {
5275 ret.push_back(f_it->first);
5276 this->erase(f_it++);
5277 } else {
5278 ++f_it;
5279 }
5280 }
5281 return ret;
5282}
5283
5289{
5290 for (auto &it : *this) {
5291 it.second.RestrictShare(via);
5292 }
5293}
5294
5299void FlowStatMap::ReleaseFlows(StationID via)
5300{
5301 for (auto &it : *this) {
5302 it.second.ReleaseShare(via);
5303 }
5304}
5305
5311{
5312 uint ret = 0;
5313 for (const auto &it : *this) {
5314 ret += (--(it.second.GetShares()->end()))->first;
5315 }
5316 return ret;
5317}
5318
5324uint FlowStatMap::GetFlowVia(StationID via) const
5325{
5326 uint ret = 0;
5327 for (const auto &it : *this) {
5328 ret += it.second.GetShare(via);
5329 }
5330 return ret;
5331}
5332
5338uint FlowStatMap::GetFlowFrom(StationID from) const
5339{
5340 FlowStatMap::const_iterator i = this->find(from);
5341 if (i == this->end()) return 0;
5342 return (--(i->second.GetShares()->end()))->first;
5343}
5344
5351uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5352{
5353 FlowStatMap::const_iterator i = this->find(from);
5354 if (i == this->end()) return 0;
5355 return i->second.GetShare(via);
5356}
5357
5359static CommandCost CheckBuildAbove_Station(TileIndex tile, [[maybe_unused]] DoCommandFlags flags, [[maybe_unused]] Axis axis, int height)
5360{
5361 StationType type = GetStationType(tile);
5362 auto bridgeable_info = GetStationBridgeableTileInfo(type);
5363
5364 switch (type) {
5365 case StationType::Rail:
5367 if (const StationSpec *spec = GetStationSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5368 break;
5369
5370 case StationType::Bus:
5371 case StationType::Truck:
5373 if (const RoadStopSpec *spec = GetRoadStopSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5374 break;
5375
5376 default: break;
5377 }
5378
5379 return IsStationBridgeAboveOk(tile, bridgeable_info, type, GetStationGfx(tile), height);
5380}
5381
5383extern const TileTypeProcs _tile_type_station_procs = {
5384 .draw_tile_proc = DrawTile_Station,
5385 .get_slope_pixel_z_proc = [](TileIndex tile, uint, uint, bool) { return GetTileMaxPixelZ(tile); },
5386 .clear_tile_proc = ClearTile_Station,
5387 .get_tile_desc_proc = GetTileDesc_Station,
5388 .get_tile_track_status_proc = GetTileTrackStatus_Station,
5389 .click_tile_proc = ClickTile_Station,
5390 .animate_tile_proc = AnimateTile_Station,
5391 .tile_loop_proc = TileLoop_Station,
5392 .change_tile_owner_proc = ChangeTileOwner_Station,
5393 .vehicle_enter_tile_proc = VehicleEnterTile_Station,
5394 .get_foundation_proc = [](TileIndex, Slope tileh) { return FlatteningFoundation(tileh); },
5395 .terraform_tile_proc = TerraformTile_Station,
5396 .check_build_above_proc = CheckBuildAbove_Station,
5397};
Base for aircraft.
void UpdateAirplanesOnNewStation(const Station *st)
Updates the status of the Aircraft heading or in the station.
const AirportFTAClass * GetAirport(const uint8_t airport_type)
Get the finite state machine of an airport type.
Definition airport.cpp:188
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition airport.h:25
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition airport.h:24
@ AirportClosed
Dummy block for indicating a closed airport.
Definition airport.h:131
@ FLYING
Vehicle is flying in the air.
Definition airport.h:78
@ NUM_AIRPORTS
Maximal number of airports in total.
Definition airport.h:41
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
Enum of the default airport tiles.
void AddAnimatedTile(TileIndex tile, bool mark_dirty)
Add the given tile to the animated tile table (if it does not exist yet).
void DeleteAnimatedTile(TileIndex tile, bool immediate)
Stops animation on the given tile.
Tile animation!
Functions related to autoslope.
bool AutoslopeCheckForAxis(TileIndex tile, int z_new, Slope tileh_new, Axis axis)
Autoslope check for tiles with something built along an axis.
Definition autoslope.h:51
bool AutoslopeCheckForEntranceEdge(TileIndex tile, int z_new, Slope tileh_new, DiagDirection entrance)
Autoslope check for tiles with an entrance on an edge.
Definition autoslope.h:31
bool AutoslopeEnabled()
Tests if autoslope is enabled for _current_company.
Definition autoslope.h:65
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Header file for bridges.
void DrawBridgeMiddle(const TileInfo *ti, BridgePillarFlags blocked_pillars)
Draw the middle bits of a bridge.
TileIndex GetSouthernBridgeEnd(TileIndex t)
Finds the southern end of a bridge starting at a middle tile.
int GetBridgeHeight(TileIndex t)
Get the height ('z') of a bridge.
Map accessor functions for bridges.
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
EnumBitSet< BridgePillarFlag, uint8_t > BridgePillarFlags
Bitset of BridgePillarFlag elements.
Definition bridge_type.h:53
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:77
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
@ Passengers
Passengers.
Definition cargotype.h:50
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does a given cargo have any cargo class from cc.
Definition cargotype.h:288
Cheats _cheats
All the cheats.
Definition cheat.cpp:16
Types related to cheating.
Iterator to iterate over all tiles belonging to an airport.
Iterator to iterate over all tiles belonging to an airport spec.
AirportGfx GetAirportGfx() const
Get the AirportGfx for the current tile.
uint Count() const
Count the number of set bits.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
bool Failed() const
Did this command fail?
Iterate a range of enum values.
Flat set implementation that uses a sorted vector for storage.
std::pair< const_iterator, bool > insert(const Tkey &key)
Insert a key into the set, if it does not already exist.
uint GetFlow() const
Get the sum of all flows from this FlowStatMap.
void PassOnFlow(StationID origin, StationID via, uint amount)
Pass on some flow, remembering it as invalid, for later subtraction from locally consumed flow.
std::vector< StationID > DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
void AddFlow(StationID origin, StationID via, uint amount)
Add some flow from "origin", going via "via".
uint GetFlowFrom(StationID from) const
Get the sum of flows from a specific station from this FlowStatMap.
void FinalizeLocalConsumption(StationID self)
Subtract invalid flows from locally consumed flow.
void ReleaseFlows(StationID via)
Release all flows at a station for specific cargo and destination.
uint GetFlowFromVia(StationID from, StationID via) const
Get the flow from a specific station via a specific other station.
uint GetFlowVia(StationID via) const
Get the sum of flows via a specific station from this FlowStatMap.
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Flow statistics telling how much flow should be sent along a link.
static const SharesMap empty_sharesmap
Static instance of FlowStat::SharesMap.
void ScaleToMonthly(uint runtime)
Scale all shares from link graph's runtime to monthly values.
void RestrictShare(StationID st)
Restrict a flow by moving it to the end of the map and decreasing the amount of unrestricted flow.
uint GetShare(StationID st) const
Get flow for a station.
StationID GetVia() const
Get a station a package can be routed to.
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
SharesMap shares
Shares of flow to be sent via specified station (or consumed locally).
void ReleaseShare(StationID st)
Release ("unrestrict") a flow by moving it to the begin of the map and increasing the amount of unres...
void ChangeShare(StationID st, int flow)
Change share for specified station.
void AppendShare(StationID st, uint flow, bool restricted=false)
Add some flow to the end of the shares map.
void Invalidate()
Reduce all flows to minimum capacity so that they don't get in the way of link usage statistics too m...
uint unrestricted
Limit for unrestricted shares.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
void Insert(const T &element)
Insert a single element in the tree.
Definition kdtree.hpp:452
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
void Queue(LinkGraph *lg)
Queue a link graph for execution.
A connected component of a link graph.
Definition linkgraph.h:35
void Merge(LinkGraph *other)
Merge a link graph with another one.
Definition linkgraph.cpp:91
TimerGameEconomy::Date LastCompression() const
Get date of last compression.
Definition linkgraph.h:249
NodeID AddNode(const Station *st)
Add a node to the component and create empty edges associated with it.
NodeID Size() const
Get the current size of the component.
Definition linkgraph.h:243
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition linkgraph.h:183
static constexpr TimerGameEconomy::Date STALE_LINK_DEPOT_TIMEOUT
Number of days before deleting links served only by vehicles stopped in depot.
Definition linkgraph.h:186
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition linkgraph.h:189
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition refresh.cpp:26
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
uint GetSpecCount() const
Get the number of allocated specs within the class.
static NewGRFClass * Get(StationClassID class_index)
StringID name
Name of this class.
bool Contains(TileIndex tile) const
Does this tile area contain a tile?
uint16_t w
The width of the area.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
void Clear()
Clears the 'tile area', i.e.
TileIndex tile
The base tile of the area.
bool IsEmpty() const
Test if this tile area is empty.
uint16_t h
The height of the area.
OrthogonalTileArea & Expand(int rad)
Expand a tile area by rad tiles in each direction, keeping within map bounds.
const RailStationTileLayout & stl
Station tile layout being iterated.
uint position
Position within iterator.
StationGfx operator*() const
Dereference operator.
uint length
Length of platforms.
std::span< const StationGfx > layout
Predefined tile layout.
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:134
SpriteID single_x
single piece of rail in X direction, without ground
Definition rail.h:144
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition rail.h:239
struct RailTypeInfo::@157247141350136173143103254227157213063052244122 strings
Strings associated with the rail type.
SpriteID single_y
single piece of rail in Y direction, without ground
Definition rail.h:145
StringID name
Name of this rail type.
Definition rail.h:184
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition rail.h:209
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition rail.h:306
struct RailTypeInfo::@332027037331076264023214171276243307073252216167 base_sprites
Struct containing the main sprites.
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition road.h:118
struct RoadTypeInfo::@070000167274302256150317022075324310363002361255 strings
Strings associated with the rail type.
StringID name
Name of this rail type.
Definition road.h:79
Generate TileIndices around a center tile or tile area, with increasing distance.
Add dynamic register values to a sprite layout.
DrawTileSpriteSpan GetLayout() const
Returns the result spritelayout after preprocessing.
uint Reroute(uint max_move, StationCargoList *dest, StationID avoid, StationID avoid2, const GoodsEntry *ge)
Routes packets with station "avoid" as next hop to a different place.
void Append(CargoPacket *cp, StationID next)
Appends the given cargo packet to the range of packets with the same next station.
uint Truncate(uint max_move=UINT_MAX, StationCargoAmountMap *cargo_per_source=nullptr)
Truncates where each destination loses roughly the same percentage of its cargo.
const StationList & GetStations()
Run a tile loop to find stations around a tile, on demand.
static constexpr TimerGameTick::Ticks STATION_LINKGRAPH_TICKS
Cycle duration for cleaning dead links.
static constexpr TimerGameTick::Ticks STATION_ACCEPTANCE_TICKS
Cycle duration for updating station acceptance.
static constexpr TimerGameTick::Ticks STATION_RATING_TICKS
Cycle duration for updating station rating.
Tile iterator wrapper.
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
static Date date
Current date in days (day counter).
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
static Date date
Current date in days (day counter).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
Iterate over all vehicles on a tile.
void DrawClearLandTile(const TileInfo *ti, uint8_t density)
Draw a ClearGround::Grass tile.
Definition clear_cmd.cpp:70
Functions related to clear (TileType::Clear) land.
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:415
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
Commands
List of commands.
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
CommandCost CheckOwnership(Owner owner, TileIndex tile)
Check whether the current owner owns something.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
GUI Functions related to companies.
static constexpr Owner OWNER_END
Last + 1 owner.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
static constexpr Owner OWNER_WATER
The tile/execution is done by "water".
Some simple functions to help with accessing containers.
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
bool CanBuildDepotByTileh(DiagDirection direction, Slope tileh)
Find out if the slope of the tile is suitable to build a depot of given direction.
Definition depot_func.h:27
void ShowDepotWindow(TileIndex tile, VehicleType type)
Opens a depot window.
bool IsValidAxis(Axis d)
Checks if an integer value is a valid Axis.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
DiagDirections AxisToDiagDirs(Axis a)
Converts an Axis to DiagDirections.
bool IsValidDiagDirection(DiagDirection d)
Checks if an integer value is a valid DiagDirection.
DiagDirection AxisToDiagDir(Axis a)
Converts an Axis to a DiagDirection.
Axis OtherAxis(Axis a)
Select the other axis as provided.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
EnumIndexArray< T, DiagDirection, DiagDirection::End > DiagDirectionIndexArray
Array with DiagDirection as index.
Direction
Defines the 8 directions on the map.
Axis
Enumeration for the two axis X and Y.
@ X
The X axis.
DiagDirection
Enumeration for diagonal directions.
@ Invalid
Flag for an invalid DiagDirection.
@ SW
Southwest.
@ End
Used for iterations.
@ SE
Southeast.
EnumBitSet< DiagDirection, uint8_t > DiagDirections
Bitset of DiagDirection elements.
Prices _price
Prices and also the fractional part.
Definition economy.cpp:109
static const uint ROAD_STOP_TRACKBIT_FACTOR
Multiplier for how many regular track bits a bay stop counts.
@ Construction
Construction costs.
Price
Enumeration of all base prices for use with Prices.
@ BuildStationTruck
Price for building lorry stations.
@ ClearStationBus
Price for destroying bus stops.
@ BuildStationBus
Price for building bus stops.
@ ClearStationAirport
Price for destroying airports.
@ ClearStationTruck
Price for destroying lorry stations.
@ BuildStationAirport
Price for building airports.
@ ClearStationDock
Price for destroying docks.
@ ClearStationRail
Price for destroying rail stations.
@ BuildStationRailLength
Additional price for building rail stations dependent on their length.
@ BuildFoundation
Price for building foundation under other constructions e.g. roads, rails, depots,...
@ BuildStationRail
Price for building rail stations.
@ BuildStationDock
Price for building docks.
@ ClearWaypointRail
Price for destroying rail waypoints.
@ ClearRail
Price for destroying rails.
void DrawRailCatenary(const TileInfo *ti)
Draws overhead wires and pylons for electric railways.
Definition elrail.cpp:554
Header file for electrified rail specific functions.
bool HasRailCatenaryDrawn(RailType rt)
Test if we should draw rail catenary.
Definition elrail_func.h:32
#define T
Climate temperate.
Definition engines.h:91
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Flat set container implementation.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition station.cpp:250
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const SpriteID SPR_RAIL_TRACK_Y
Definition sprites.h:449
static const SpriteID SPR_MONO_TRACK_X_SNOW
Definition sprites.h:496
static const SpriteID SPR_MGLV_TRACK_Y_SNOW
Definition sprites.h:508
static const SpriteID SPR_MONO_TRACK_Y
Definition sprites.h:491
static const SpriteID SPR_MONO_TRACK_Y_SNOW
Definition sprites.h:495
static const SpriteID SPR_MONO_TRACK_X
Definition sprites.h:492
static const SpriteID SPR_RAIL_TRACK_X_SNOW
Definition sprites.h:454
static const SpriteID SPR_MGLV_TRACK_X
Definition sprites.h:506
static const SpriteID SPR_RAIL_TRACK_Y_SNOW
Definition sprites.h:453
static const SpriteID SPR_MGLV_TRACK_X_SNOW
Definition sprites.h:509
static const SpriteID SPR_MGLV_TRACK_Y
Definition sprites.h:505
static const SpriteID SPR_RAIL_TRACK_X
Definition sprites.h:450
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:59
@ TownEdge
Edge of the town; roads without pavement.
Definition house.h:60
Base of all industries.
bool IsTileForestIndustry(TileIndex tile)
Check whether the tile is a forest.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
IndustryID GetIndustryIndex(Tile t)
Get the industry ID of the given tile.
static const IndustryType NUM_INDUSTRYTYPES
total number of industry types, new and old; limited to 240 because we need some special ids like IT_...
@ Extractive
Like mines.
const TileTypeProcs _tile_type_station_procs
TileTypeProcs definitions for TileType::Station tiles.
Definition landscape.cpp:59
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
void DrawFoundation(TileInfo *ti, Foundation f)
Draw foundation f at tile ti.
uint GetFoundationSpriteBlock(TileIndex tile)
Get the sprite block to use for a foundation.
uint ApplyPixelFoundationToSlope(Foundation f, Slope &s)
Applies a foundation to a slope.
Definition landscape.h:128
Point RemapCoords2(int x, int y)
Map 3D world or tile coordinate to equivalent 2D coordinate as used in the viewports and smallmap.
Definition landscape.h:97
Command definitions related to landscape (slopes etc.).
@ Arctic
Landscape with snow levels.
@ Tropic
Landscape with distinct rainforests and deserts,.
Some typedefs for the main game.
EnumBitSet< EdgeUpdateMode, uint8_t > EdgeUpdateModes
Bitset of EdgeUpdateMode elements.
@ Increase
Increase capacity.
@ Manual
Manual distribution. No link graph calculations are run.
#define Point
Macro that prevents name conflicts between included headers.
uint DistanceFromEdge(TileIndex tile)
Param the minimum distance to an edge.
Definition map.cpp:228
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition map.cpp:200
TileIndex TileAddWrap(TileIndex tile, int addx, int addy)
This function checks if we add addx/addy to tile, if we do wrap around the edges.
Definition map.cpp:119
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:168
TileIndexDiff ToTileIndexDiff(TileIndexDiffC tidc)
Return the offset between two tiles from a TileIndexDiffC struct.
Definition map_func.h:444
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:559
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
@ Buoy
Buoy without underlying water.
Definition newgrf.h:39
@ RoadStops
Road stops feature.
Definition newgrf.h:102
@ Stations
Stations feature.
Definition newgrf.h:86
@ Airports
Airports feature.
Definition newgrf.h:95
@ AirportTiles
Airport tiles feature.
Definition newgrf.h:99
static constexpr AirportGfx AIRPORTGFX_CLEARTILE_SPECIALCHECK
Sentinel marker in airport layout to perform a clear tile check.
StationGfx GetTranslatedAirportTileID(StationGfx gfx)
Do airporttile gfx ID translation for NewGRFs.
NewGRF handling of airport tiles.
@ NoAnimation
There is no animation.
@ DrawTileLayout
Use callback to select a tile layout to use when drawing.
@ Avail
Availability of station in construction window.
@ SlopeCheck
Check slope of new station tiles.
@ StationRatingCalc
custom station rating for this cargo type
@ CBID_STATION_BUILD_TILE_LAYOUT
Called when building a station to customize the tile layout.
@ CBID_STATION_DRAW_TILE_LAYOUT
Choose a tile layout to draw, instead of the standard range.
@ CBID_CARGO_STATION_RATING_CALC
Called to calculate part of a station rating.
@ CBID_STATION_AVAILABILITY
Determine whether a newstation should be made available to build.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
@ Avail
Availability of road stop in construction window.
SpriteID GetCanalSprite(CanalFeature feature, TileIndex tile)
Lookup the base sprite to use for a canal.
Handling of NewGRF canals.
Cargo support for NewGRFs.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
void ErrorUnknownCallbackResult(GrfID grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
GRFConfig * GetGRFConfig(GrfID grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
@ Any
Use first found.
Functions/types related to NewGRF debugging.
void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index)
Delete inspect window for a given feature and index.
void TriggerHouseAnimation_WatchedCargoAccepted(TileIndex tile, CargoTypes trigger_cargoes)
Run watched cargo accepted callback for a house.
Functions related to NewGRF houses.
SpriteID GetCustomRailSprite(const RailTypeInfo *rti, TileIndex tile, RailSpriteType rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
NewGRF handling of rail types.
void TriggerRoadStopRandomisation(BaseStation *st, TileIndex tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger road stop randomisation.
void DeallocateSpecFromRoadStop(BaseStation *st, uint8_t specindex)
Deallocate a RoadStopSpec from a Station.
std::optional< uint8_t > AllocateSpecToRoadStop(const RoadStopSpec *spec, BaseStation *st)
Allocate a RoadStopSpec to a Station.
void AssignSpecToRoadStop(const RoadStopSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated RoadStopSpec specindex to a Station.
NewGRF definitions and structures for road stops.
@ Overlay
Drive-through stops: Draw the road overlay, e.g. pavement.
@ WaypGround
Waypoints: Draw the sprite layout ground tile (on top of the road).
@ Road
Bay stops: Draw the road itself.
bool IsWaypointClass(const RoadStopClass &cls)
Test if a RoadStopClass is the waypoint class.
PoolID< uint16_t, struct RoadStopClassIDTag, UINT16_MAX, UINT16_MAX > RoadStopClassID
Class IDs for stations.
EnumBitSet< RoadStopDrawMode, uint8_t > RoadStopDrawModes
Bitset of RoadStopDrawMode elements.
@ ROADSTOPTYPE_FREIGHT
This RoadStop is for freight (truck) stops.
@ ROADSTOPTYPE_ALL
This RoadStop is for both types of station road stops.
@ ROADSTOPTYPE_PASSENGER
This RoadStop is for passenger (bus) stops.
@ NoCatenary
Do not show catenary.
@ DriveThroughOnly
Stop is drive-through only.
@ DrawModeRegister
Read draw mode from register 0x100.
SpriteID GetCustomRoadSprite(const RoadTypeInfo *rti, TileIndex tile, RoadSpriteType rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
NewGRF handling of road types.
SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
Resolve sprites for drawing a station tile.
SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
Resolve the sprites for custom station foundations.
void AssignSpecToStation(const StationSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated StationSpec specindex to a Station.
void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
Deallocate a StationSpec from a Station.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, uint8_t plat_len, uint8_t numtracks)
Check the slope of a tile of a new station.
uint32_t GetPlatformInfo(StationGfx gfx, int platforms, int length, int platform, int position, bool centred)
Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
std::optional< uint8_t > AllocateSpecToStation(const StationSpec *spec, BaseStation *st)
Allocate a StationSpec to a Station.
Header file for NewGRF stations.
@ CustomFoundations
Draw custom foundations.
@ SeparateGround
Use different sprite set for ground sprites.
@ ExtendedFoundations
Extended foundation block instead of simple.
NewGRFClass< StationSpec, StationClassID > StationClass
Class containing information relating to station classes.
PoolID< uint16_t, struct StationClassIDTag, UINT16_MAX, UINT16_MAX > StationClassID
Class IDs for stations.
Functions related to news.
void AddNewsItem(EncodedString &&headline, NewsType type, NewsStyle style, NewsFlags flags, NewsReference ref1={}, NewsReference ref2={}, std::unique_ptr< NewsAllocatedData > &&data=nullptr, AdviceType advice_type=AdviceType::Invalid)
Add a new newsitem to be shown.
Definition news_gui.cpp:919
@ Acceptance
A type of cargo is (no longer) accepted.
Definition news_type.h:46
@ Small
Small news item. (Information window with text and viewport).
Definition news_type.h:82
@ InColour
News item is shown in colour (otherwise it is shown in black & white).
Definition news_type.h:93
@ LinkGraph
A game paused due to the link graph schedule lagging.
Definition openttd.h:78
@ Editor
In the scenario editor.
Definition openttd.h:21
@ Menu
In the main menu.
Definition openttd.h:19
Functions related to order backups.
Train * GetTrainForReservation(TileIndex tile, Track track)
Find the train which has reserved a specific path.
Definition pbs.cpp:345
void SetRailStationPlatformReservation(TileIndex start, DiagDirection dir, bool b)
Set the reservation for a complete station platform.
Definition pbs.cpp:57
PBS support routines.
bool ValParamRailType(const RailType rail)
Validate functions for rail building.
Definition rail.cpp:92
@ Ground
Main group of ground images.
Definition rail.h:45
@ Overlay
Images for overlaying track.
Definition rail.h:44
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition rail.h:448
bool HasPowerOnRail(RailType enginetype, RailType tiletype)
Checks if an engine of the given RailType got power on a tile with a given RailType.
Definition rail.h:396
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:320
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition rail.h:63
@ X
Piece of rail in X direction.
Definition rail.h:64
@ Y
Piece of rail in Y direction.
Definition rail.h:65
Command definitions for rail.
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition rail_map.h:136
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
void MakeRailNormal(Tile t, Owner o, TrackBits b, RailType r)
Make the given tile a normal rail.
Definition rail_map.h:624
TrackBits GetRailReservationTrackBits(Tile t)
Returns the reserved track bits of the tile.
Definition rail_map.h:194
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:26
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition rail_type.h:33
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
Declaration of link refreshing utility.
bool ValParamRoadType(RoadType roadtype)
Validate functions for rail building.
Definition road.cpp:164
bool HasPowerOnRoad(RoadType enginetype, RoadType tiletype)
Checks if an engine of the given RoadType got power on a tile with a given RoadType.
Definition road.h:232
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
@ Roadstop
Required: Bay stop surface.
Definition road.h:49
@ Ground
Required: Main group of ground images.
Definition road.h:41
@ Overlay
Optional: Images for overlaying track.
Definition road.h:40
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition road.h:242
void DrawRoadGroundSprites(const TileInfo *ti, RoadBits road, RoadBits tram, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, Roadside roadside, bool snow_or_desert)
Draw road ground sprites.
void DrawRoadCatenary(const TileInfo *ti)
Draws the catenary for the given tile.
void UpdateCompanyRoadInfrastructure(RoadType rt, Owner o, int count)
Update road infrastructure counts for a company.
Definition road_cmd.cpp:184
CommandCost CheckAllowRemoveRoad(TileIndex tile, RoadBits remove, Owner owner, RoadTramType rtt, DoCommandFlags flags, bool town_check)
Is it allowed to remove the given road bits from the given tile?
Definition road_cmd.cpp:256
void DrawRoadOverlays(const TileInfo *ti, PaletteID pal, const RoadTypeInfo *road_rti, const RoadTypeInfo *tram_rti, uint road_offset, uint tram_offset, bool draw_underlay)
Draw road underlay and overlay sprites.
Functions related to roads.
RoadBits AxisToRoadBits(Axis a)
Create the road-part which belongs to the given Axis.
Definition road_func.h:93
Functions used internally by the roads.
bool MayHaveRoad(Tile t)
Test whether a tile can have road/tram types.
Definition road_map.cpp:21
RoadBits GetAnyRoadBits(Tile tile, RoadTramType rtt, bool straight_tunnel_bridge_entrance)
Returns the RoadBits on an arbitrary tile Special behaviour:
Definition road_map.cpp:54
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:261
RoadType GetRoadTypeRoad(Tile t)
Get the road type for RoadTramType being RoadTramType::Road.
Definition road_map.h:152
RoadBits GetRoadBits(Tile t, RoadTramType rtt)
Get the present road bits for a specific road type.
Definition road_map.h:112
DisallowedRoadDirections GetDisallowedRoadDirections(Tile t)
Gets the disallowed directions.
Definition road_map.h:311
bool HasTileRoadType(Tile t, RoadTramType rtt)
Check if a tile has a road or a tram road type.
Definition road_map.h:221
RoadType GetRoadTypeTram(Tile t)
Get the road type for RoadTramType being RoadTramType::Tram.
Definition road_map.h:163
void MakeRoadNormal(Tile t, RoadBits bits, RoadType road_rt, RoadType tram_rt, TownID town, Owner road, Owner tram)
Make a normal road tile.
Definition road_map.h:646
RoadBits GetAllRoadBits(Tile tile)
Get all set RoadBits on the given tile.
Definition road_map.h:125
RoadType GetRoadType(Tile t, RoadTramType rtt)
Get the road type for the given RoadTramType.
Definition road_map.h:175
static bool IsNormalRoadTile(Tile t)
Return whether a tile is a normal road tile.
Definition road_map.h:58
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition road_map.h:244
Roadside
The possible road side decorations.
Definition road_map.h:483
@ Paved
Road with paved sidewalks.
Definition road_map.h:486
@ Barren
Road on barren land.
Definition road_map.h:484
@ Grass
Road on grass.
Definition road_map.h:485
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
Definition road_type.h:67
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:65
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:68
static constexpr RoadTramTypes ROADTRAMTYPES_ALL
All possible RoadTramTypes.
Definition road_type.h:49
RoadType
The different roadtypes we support.
Definition road_type.h:24
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:29
RoadTramType
The different types of road type.
Definition road_type.h:38
@ Tram
Tram type.
Definition road_type.h:40
@ Road
Road type.
Definition road_type.h:39
Base class for roadstops.
Road vehicle states.
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
@ RVSB_ROAD_STOP_TRACKDIR_MASK
Only bits 0 and 3 are used to encode the trackdir for road stops.
Definition roadveh.h:57
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base for ships.
bool IsShipDestinationTile(TileIndex tile, StationID station)
Test if a tile is a docking tile for the given station.
Definition ship_cmd.cpp:575
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition signal.cpp:597
@ Enter
signal entering the block found
Definition signal.cpp:261
static constexpr int GetSlopeMaxZ(Slope s)
Returns the height of the highest corner of a slope relative to TileZ (= minimal height).
Definition slope_func.h:170
static constexpr bool IsSteepSlope(Slope s)
Checks if a slope is steep.
Definition slope_func.h:36
Foundation FlatteningFoundation(Slope s)
Returns the foundation needed to flatten a slope.
Definition slope_func.h:377
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:249
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:54
@ Leveled
The tile is leveled up to a flat slope.
Definition slope_type.h:121
void DrawRailTileSeqInGUI(int x, int y, const DrawTileSprites *dts, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence in GUI with railroad specifics.
Definition sprite.h:122
void DrawRailTileSeq(const struct TileInfo *ti, const DrawTileSprites *dts, TransparencyOption to, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence on tile with railroad specifics.
Definition sprite.h:108
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition sprite.h:207
static const SpriteID SPR_TRAMWAY_TRAM
Definition sprites.h:304
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1794
static const SpriteID SPR_FLAT_SNOW_DESERT_TILE
Definition sprites.h:689
static const PaletteID PALETTE_TO_GREY
Definition sprites.h:1778
static const SpriteID SPR_IMG_BUOY
Definition sprites.h:1464
static const SpriteID SPR_FLAT_GRASS_TILE
Definition sprites.h:677
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1732
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1722
static constexpr uint8_t PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition sprites.h:1735
CommandCost CheckStationSpread(TileArea area, const TileArea &new_area)
Check if adding a new area to a station will exceed the maximum station spread.
Definition station.cpp:526
Base classes/functions for stations.
void ForAllStationsAroundTiles(const TileArea &ta, Func func)
Call a function on all stations that have any part of the requested area within their catchment.
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
std::tuple< CommandCost, StationID > CmdMoveStationName(DoCommandFlags flags, StationID station_id, TileIndex tile)
Move a station name.
static StringID GetBridgeTooLowMessageForStationType(StationType type)
Get station-type-specific string for a bridge that is too low.
static void GetTileDesc_Station(TileIndex tile, TileDesc &td)
Tile callback function signature for obtaining a tile description.
static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reuse, TileArea area, StationNaming name_class)
Common part of building various station parts and possibly attaching them to an existing one.
static void MakeStationSpreadAreaSmaller(BaseStation *st)
Make the spread area of a station as small as possible.
static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlags flags)
Remove a rail waypoint.
void CcMoveStationName(Commands, const CommandCost &result, StationID station_id)
Callback function that is called after a name is moved.
CommandCost IsRailStationBridgeAboveOk(TileIndex tile, const StationSpec *spec, StationType type, StationGfx layout)
Test if a rail station can be built below a bridge.
uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
Get a possible noise reduction factor based on distance from town center.
static constexpr DiagDirectionIndexArray< uint8_t > _dock_w_chk
X dimension of dock for each direction.
static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
Tile callback function signature of the terraforming callback.
CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector< T * > &affected_stations, DoCommandFlags flags, Money removal_cost, bool keep_rail)
Remove a number of tiles from any rail station within the area.
static CommandCost CalculateRailStationCost(TileArea tile_area, DoCommandFlags flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
Calculates cost of new rail stations within the area.
static StringID GenerateStationName(Station *st, TileIndex tile, StationNaming name_class)
Generate a station name for the given station at the given location.
void ClearDockingTilesCheckingNeighbours(TileIndex tile)
Clear docking tile status from tiles around a removed dock, if the tile has no neighbours which would...
bool(* CMSAMatcher)(TileIndex tile)
Function to check whether the given tile matches some criterion.
CommandCost IsRoadStationBridgeAboveOk(TileIndex tile, const RoadStopSpec *spec, StationType type, StationGfx layout)
Test if a road station can be built below a bridge.
bool IsHangar(Tile t)
Check whether the given tile is a hangar.
Town * AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIteratorWrapper< AirportTileIterator, AirportTileTableIterator > &&iter, uint &mindist)
Finds the town nearest to given airport.
static Station * GetClosestDeletedStation(TileIndex tile)
Find the closest deleted station of the current company.
CommandCost CmdRenameStation(DoCommandFlags flags, StationID station_id, const std::string &text)
Rename a station.
std::pair< CargoArray, CargoTypes > GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
Get the acceptance of cargoes around the tile in 1/8.
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlags flags)
Remove an airport.
static void TileLoop_Station(TileIndex tile)
Tile callback function signature for running periodic tile updates.
static bool CMSAMine(TileIndex tile)
Check whether the tile is a mine.
void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
Increase capacity for a link stat given by station cargo and next hop.
static CommandCost CheckFlatLandRoadStop(TileIndex cur_tile, int &allowed_z, const RoadStopSpec *spec, DoCommandFlags flags, DiagDirections invalid_dirs, bool is_drive_through, StationType station_type, Axis axis, StationID *station, RoadType rt)
Checks if a road stop can be built at the given tile.
static CommandCost RemoveGenericRoadStop(DoCommandFlags flags, const TileArea &roadstop_area, bool road_waypoint, bool remove_road)
Remove a tile area of road stop or road waypoints.
static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount=UINT_MAX)
Truncate the cargo by a specific amount.
CommandCost CmdRemoveFromRailWaypoint(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a waypoint.
StationNaming
Station types a station could be named after.
@ Dock
Ship dock.
@ Rail
Railway station.
@ Road
Truck or bus stop.
@ Oilrig
Heliport of an oilrig.
@ Heliport
Standalone heliport.
@ Airport
Airport for fixed wing aircraft.
CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
Find a nearby waypoint that joins this waypoint.
CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station_to_join, bool adjacent)
Build a dock/haven.
CommandCost IsBuoyBridgeAboveOk(TileIndex tile)
Test if a buoy can be built below a bridge.
static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlags flags)
Checks if an airport can be built at the given location and clear the area.
CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index=-1)
Remove a road waypoint.
CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
Look for a station owned by the given company around the given tile area.
CommandCost CmdRemoveRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
Remove bus or truck stops.
static VehicleEnterTileStates VehicleEnterTile_Station(Vehicle *v, TileIndex tile, int x, int y)
Tile callback function for a vehicle entering a tile.
static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
Tile callback function signature for changing the owner of a tile.
bool HasStationInUse(StationID station, bool include_company, CompanyID company)
Tests whether the company's vehicles have this station in orders.
static int CountMapSquareAround(TileIndex tile, CMSAMatcher cmp)
Counts the numbers of tiles matching a specific type in the area around.
CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through, DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build a bus or truck stop.
static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
Get station tile flags for the given StationGfx.
static CommandCost IsDockBridgeAboveOk(TileIndex tile, StationGfx layout)
Test if a dock can be built below a bridge.
static bool DrawCustomStationFoundations(const StationSpec *statspec, BaseStation *st, TileInfo *ti, StationGfx gfx)
Draw custom station foundations for a NewGRF station if provided.
const DrawTileSprites * GetStationTileLayout(StationType st, uint8_t gfx)
Get station tile layout for a station type and its station gfx.
CommandCost CmdRemoveFromRoadWaypoint(DoCommandFlags flags, TileIndex start, TileIndex end)
Remove road waypoints.
void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
static constexpr DiagDirectionIndexArray< TileIndexDiffC > _dock_tileoffs_chkaround
Offset of northern-most dock tile for each direction.
CommandCost ClearTile_Station(TileIndex tile, DoCommandFlags flags)
Tile callback function signature for clearing a tile.
static std::pair< CargoArray, CargoTypes > GetAcceptanceAroundStation(const Station *st)
Get the acceptance of cargoes around the station in.
static void UpdateStationRating(Station *st)
Periodic update of a station's rating.
static TrackStatus GetTileTrackStatus_Station(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Tile callback function signature for getting the possible tracks that can be taken on a given tile by...
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
static void DrawTile_Station(TileInfo *ti)
Tile callback function signature for drawing a tile and its contents to the screen.
static bool CMSAWater(TileIndex tile)
Check whether the tile is water.
CommandCost CmdBuildAirport(DoCommandFlags flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
Place an Airport.
void TriggerWatchedCargoCallbacks(Station *st)
Run the watched cargo callback for all houses in the catchment area.
static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlags flags)
Check if a drive-through road stop tile can be cleared.
static RoadStop ** FindRoadStopSpot(bool truck_station, Station *st)
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
static void RestoreTrainReservation(Train *v)
Restore platform reservation during station building/removing.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
static std::span< const BridgeableTileInfo > GetStationBridgeableTileInfo(StationType type)
Get bridgeable tile information for a station type.
static bool CMSATree(TileIndex tile)
Check whether the tile is a tree.
void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
Forcibly modify station ratings near a given tile.
CommandCost RemoveRailStation(T *st, DoCommandFlags flags, Money removal_cost)
Remove a rail station/waypoint.
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this road stop.
CommandCost CmdOpenCloseAirport(DoCommandFlags flags, StationID station_id)
Open/close an airport to incoming aircraft.
static const IntervalTimer< TimerGameEconomy > _economy_stations_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Station}, [](auto) { for(Station *st :Station::Iterate()) { for(GoodsEntry &ge :st->goods) { ge.status.Set(GoodsEntry::State::LastMonth, ge.status.Test(GoodsEntry::State::CurrentMonth));ge.status.Reset(GoodsEntry::State::CurrentMonth);} } })
Economy monthly loop for stations.
static CommandCost CheckFlatLandRailStation(TileIndex tile_cur, TileIndex north_tile, int &allowed_z, DoCommandFlags flags, Axis axis, StationID *station, RailType rt, std::vector< Train * > &affected_vehicles, StationClassID spec_class, uint16_t spec_index, uint8_t plat_len, uint8_t numtracks)
Checks if a rail station can be built at the given tile.
static TileIndex FindDockLandPart(TileIndex t)
Find the part of a dock that is land-based.
static CommandCost CheckBuildAbove_Station(TileIndex tile, DoCommandFlags flags, Axis axis, int height)
Tile callback function signature to test if a bridge can be built above a tile.
static void FreeTrainReservation(Train *v)
Clear platform reservation during station building/removing.
static bool ClickTile_Station(TileIndex tile)
Tile callback function signature for clicking a tile.
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
CommandCost CalculateRoadStopCost(TileArea tile_area, DoCommandFlags flags, bool is_drive_through, StationType station_type, const RoadStopSpec *roadstopspec, Axis axis, DiagDirection ddir, StationID *station, RoadType rt, Money unit_cost)
Calculates cost of new road stops within the area.
CargoTypes GetCargoWaitingMask(const Station *st)
Get a mask of the cargo types that have cargo waiting at the station.
static CommandCost RemoveDock(TileIndex tile, DoCommandFlags flags)
Remove a dock.
static void AnimateTile_Station(TileIndex tile)
Tile callback function signature for animating a tile.
bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a ra...
CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
Get the cargo types being produced around the tile (in a rectangle).
CommandCost CmdRemoveFromRailStation(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
Remove a single tile from a rail station.
static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
Find a nearby station that joins this station.
void DeleteStaleLinks(Station *from)
Check all next hops of cargo packets in this station for existence of a a valid link they may use to ...
static BridgePillarFlags GetStationBlockedPillars(std::span< const BridgeableTileInfo > bridgeable_info, uint8_t layout)
Get blocked pillar information for a station tile.
CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge=true)
Checks if the given tile is buildable, flat and has a certain height.
CommandCost FindJoiningBaseStation(StringID error_message, StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
Find a nearby station that joins this station.
static constexpr DiagDirectionIndexArray< uint8_t > _dock_h_chk
Y dimension of dock for each direction.
static bool StationHandleBigTick(BaseStation *st)
This function is called for each station once every 250 ticks.
static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
Add news item for when a station changes which cargoes it accepts.
CommandCost CmdBuildRailStation(DoCommandFlags flags, TileIndex tile_org, RailType rt, Axis axis, uint8_t numtracks, uint8_t plat_len, StationClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
Build rail station.
static void DeleteStationIfEmpty(BaseStation *st)
This is called right after a station was deleted.
static CommandCost IsStationBridgeAboveOk(TileIndex tile, std::span< const BridgeableTileInfo > bridgeable_info, StationType type, StationGfx layout, int bridge_height, StringID disallowed_msg=INVALID_STRING_ID)
Test if a bridge can be built above a station.
Command definitions related to stations.
Functions related to stations.
void ShowStationViewWindow(StationID station)
Opens StationViewWindow for given station.
@ Count
by amount of cargo
Declarations for accessing the k-d tree of stations.
void ForAllStationsRadius(TileIndex center, uint radius, Func func)
Call a function on all stations whose sign is within a radius of a center tile.
Sprites to use and how to display them for station tiles.
Functions related to station layouts.
void MakeAirport(Tile t, Owner o, StationID sid, uint8_t section, WaterClass wc)
Make the given tile an airport tile.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:42
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:66
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:78
void MakeRoadStop(Tile t, Owner o, StationID sid, RoadStopType rst, RoadType road_rt, RoadType tram_rt, DiagDirection d)
Make the given tile a roadstop tile.
void SetCustomStationSpecIndex(Tile t, uint8_t specindex)
Set the custom station spec for this tile.
void SetStationTileHaveWires(Tile t, bool b)
Set the catenary wires state of the rail station.
bool IsAirport(Tile t)
Is this station tile an airport?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
uint GetCustomRoadStopSpecIndex(Tile t)
Get the custom road stop spec for this tile.
static const int GFX_DOCK_BASE_WATER_PART
The offset for the water parts.
Definition station_map.h:33
bool IsBuoy(Tile t)
Is tile t a buoy tile?
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
bool IsRoadWaypoint(Tile t)
Is the station at t a road waypoint?
void MakeDriveThroughRoadStop(Tile t, Owner station, Owner road, Owner tram, StationID sid, StationType rst, RoadType road_rt, RoadType tram_rt, Axis a)
Make the given tile a drivethrough roadstop tile.
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
static Roadside GetRoadWaypointRoadside(Tile tile)
Get the decorations of a road waypoint.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
Track GetRailStationTrack(Tile t)
Get the rail track of a rail station tile.
static void ToggleRoadWaypointOnSnowOrDesert(Tile t)
Toggle the snow/desert state of a road waypoint tile.
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
bool HasStationTileRail(Tile t)
Has this station tile a rail?
StationGfx GetAirportGfx(Tile t)
Get the station graphics of this airport tile.
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
bool IsRailWaypoint(Tile t)
Is this station tile a rail waypoint?
bool IsRailStation(Tile t)
Is this station tile a rail station?
Definition station_map.h:90
bool IsDockTile(Tile t)
Is tile t a dock tile?
static void SetRoadWaypointRoadside(Tile tile, Roadside s)
Set the decorations of a road waypoint.
void SetStationTileRandomBits(Tile t, uint8_t random_bits)
Set the random bits for a station tile.
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
void MakeOilrig(Tile t, StationID sid, WaterClass wc)
Make the given tile an oilrig tile.
DiagDirection GetDockDirection(Tile t)
Get the direction of a dock.
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
static bool IsRoadWaypointOnSnowOrDesert(Tile t)
Check if a road waypoint tile has snow/desert.
bool IsRoadWaypointTile(Tile t)
Is this tile a station tile and a road waypoint?
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
uint8_t StationGfx
Index of station graphics.
Definition station_map.h:18
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
bool HasStationRail(Tile t)
Has this station tile a rail?
static const int GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET
The offset for the drive through parts.
Definition station_map.h:34
Axis GetDriveThroughStopAxis(Tile t)
Gets the axis of the drive through stop.
void SetStationTileHavePylons(Tile t, bool b)
Set the catenary pylon state of the rail station.
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
void MakeRailStation(Tile t, Owner o, StationID sid, Axis a, uint8_t section, RailType rt)
Make the given tile a rail station tile.
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
void MakeDock(Tile t, Owner o, StationID sid, DiagDirection d, WaterClass wc)
Make the given tile a dock tile.
DiagDirection GetBayRoadStopDir(Tile t)
Gets the direction the bay road stop entrance points towards.
bool IsDock(Tile t)
Is tile t a dock tile?
bool IsAnyRoadStopTile(Tile t)
Is tile t a road stop station?
void SetStationTileBlocked(Tile t, bool b)
Set the blocked state of the rail station.
RoadStopType GetRoadStopType(Tile t)
Get the road stop type of this tile.
Definition station_map.h:54
void SetCustomRoadStopSpecIndex(Tile t, uint8_t specindex)
Set the custom road stop spec for this tile.
RoadStopType
Types of RoadStops.
@ Bus
A standard stop for buses.
@ Truck
A standard stop for trucks.
@ End
End of valid types.
@ Dock
Station with a dock.
@ Waypoint
Station is a waypoint.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
StationType
Station types.
@ Dock
Ship port.
@ Rail
Railways/train station.
@ Bus
Road stop for busses.
@ Truck
Road stop for trucks.
@ RailWaypoint
Waypoint for trains.
@ Buoy
Waypoint for ships.
@ RoadWaypoint
Waypoint for trucks and busses.
@ Oilrig
Heliport on an oil rig.
@ Airport
Airports and heliports, excluding the ones on oil rigs.
@ NewCargo
Trigger station on new cargo arrival.
std::set< Station *, StationCompare > StationList
List of stations.
@ Built
Trigger tile when built.
@ TileLoop
Trigger in the periodic tile loop.
@ NewCargo
Trigger station on new cargo arrival.
@ AcceptanceTick
Trigger station every 250 ticks.
EnumBitSet< StationFacility, uint8_t > StationFacilities
Bitset of StationFacility elements.
static const uint MAX_LENGTH_STATION_NAME_CHARS
The maximum length of a station name in characters including '\0'.
@ Built
Triggered when the airport is built (for all tiles at the same time).
@ TileLoop
Triggered in the periodic tile loop.
@ NewCargo
Triggered when new cargo arrives at the station (for all tiles at the same time).
@ AcceptanceTick
Triggered every 250 ticks (for all tiles at the same time).
Types related to the station widgets.
@ WID_SV_CLOSE_AIRPORT
'Close airport' button.
@ WID_SV_ROADVEHS
List of scheduled road vehs button.
@ WID_SV_ACCEPT_RATING_LIST
List of accepted cargoes / rating of cargoes.
@ WID_SV_SHIPS
List of scheduled ships button.
@ WID_SV_TRAINS
List of scheduled trains button.
Definition of base types and functions in a cross-platform compatible way.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition string.cpp:350
Functions related to low-level strings.
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:75
@ Airplanes
Can planes land on this airport type?
Definition airport.h:165
Defines the data structure for an airport.
StringID name
name of this airport
SubstituteGRFFileProps grf_prop
Properties related to the grf file.
std::vector< AirportTileLayout > layouts
List of layouts composing the airport.
bool IsWithinMapBounds(uint8_t table, TileIndex index) const
Check if the airport would be within the map bounds at the given tile.
uint8_t size_y
size of airport in y direction
uint8_t size_x
size of airport in x direction
static const AirportSpec * Get(uint8_t type)
Retrieve airport spec for the given airport.
std::span< const HangarTileTable > depots
Position of the depots on the airports.
bool IsAvailable() const
Check whether this airport is available to build.
uint8_t noise_level
noise that this airport generates
Defines the data structure of each individual tile of an airport.
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
SubstituteGRFFileProps grf_prop
properties related the the grf file
StringID name
Tile Subname string, land information on this tile will give you "AirportName (TileSubname)".
static const AirportTileSpec * GetByTile(TileIndex tile)
Retrieve airport tile spec for the given airport tile.
All airport-related information.
AirportBlocks blocks
stores which blocks on the airport are taken. was 16 bit earlier on, then 32
TileIndex GetRotatedTileFromOffset(TileIndexDiffC tidc) const
Add the tileoffset to the base tile of this airport but rotate it first.
uint GetHangarNum(TileIndex tile) const
Get the hangar number of the hangar at a specific tile.
Direction rotation
How this airport is rotated.
uint8_t type
Type of this airport,.
PersistentStorage * psa
Persistent storage for NewGRF airports.
uint GetNumHangars() const
Get the number of hangars on this airport.
TileIndex GetHangarTile(uint hangar_num) const
Get the first tile of the given hangar.
const AirportSpec * GetSpec() const
Get the AirportSpec that from the airport type of this airport.
uint8_t layout
Airport layout number.
Base class for all station-ish types.
StringID string_id
Default name (town area) of station.
TileIndex xy
Base tile of the station.
virtual void MoveSign(TileIndex new_xy)
Move this station's main coordinate somewhere else.
std::vector< SpecMapping< StationSpec > > speclist
List of rail station specs of this station.
StationFacilities facilities
The facilities that this station has.
std::string cached_name
NOSAVE: Cache of the resolved name of the station, if not using a custom name.
TileArea train_station
Tile area the train 'station' part covers.
StationAnimationTriggers cached_anim_triggers
NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
Owner owner
The owner of this station.
virtual void UpdateVirtCoord()=0
Update the coordinated of the sign (as shown in the viewport).
uint8_t delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
StationAnimationTriggers cached_roadstop_anim_triggers
NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing sh...
bool IsInUse() const
Check whether the base station currently is in use; in use means that it is not scheduled for deletio...
Town * town
The town this station is associated with.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
TrackedViewportSign sign
NOSAVE: Dimensions of sign.
TimerGameCalendar::Date build_date
Date of construction.
std::string name
Custom name.
TileArea spread
NOSAVE: Station spread tile area.
VehicleType type
Type of vehicle.
Class for storing amounts of cargo.
Definition cargo_type.h:120
Specification of a cargo type.
Definition cargotype.h:76
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
CargoType Index() const
Determines index of this cargospec.
Definition cargotype.h:110
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition cargotype.h:239
uint32_t station
Count of company owned station tiles.
std::array< uint32_t, RAILTYPE_END > rail
Count of company owned track bits for each rail type.
uint32_t water
Count of company owned track bits for canals.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
T y
Y coordinate.
T x
X coordinate.
T z
Z coordinate.
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:76
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:55
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:56
std::string GetName() const
Get the name of this grf.
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
bool HasGrfFile() const
Test if this entity was introduced by NewGRF.
StationSettings station
settings related to station management
FlowStatMap flows
Planned flows through this station.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
uint max_waiting_cargo
Max cargo from this station waiting at any station.
bool HasRating() const
Does this cargo have a rating at this station?
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
States status
Status of this cargo, see State.
NodeID node
ID of node in link graph referring to this goods entry.
@ LastMonth
Set when cargo was delivered for final delivery last month.
@ Acceptance
Set when the station accepts the cargo currently for final deliveries.
@ Rating
This indicates whether a cargo has a rating at the station.
@ AcceptedBigtick
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
@ CurrentMonth
Set when cargo was delivered for final delivery this month.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
uint8_t amount_fract
Fractional part of the amount in the cargo list.
LinkGraphID link_graph
Link graph this station belongs to.
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
uint8_t rating
Station rating for this cargo.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
GoodsEntryData & GetOrCreateData()
Get optional cargo packet/flow data.
uint AvailableCount() const
Returns sum of cargo still available for loading at the station.
StationID GetVia(StationID source) const
Get the best next hop for a cargo packet from station source.
Defines the data structure for constructing industry.
SubstituteGRFFileProps grf_prop
properties related to the grf file
StringID name
Displayed name of the industry.
StringID station_name
Default name for nearby station.
bool enabled
entity still available (by default true).newgrf can disable it, though
IndustryLifeTypes life_type
This is also known as Industry production flag, in newgrf specs.
Defines the internal data of a functional industry.
Definition industry.h:64
IndustryType type
type of industry.
Definition industry.h:117
ProducedCargoes produced
produced cargo slots
Definition industry.h:112
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition industry.h:118
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:253
TileArea location
Location of the industry.
Definition industry.h:108
Station * neutral_station
Associated neutral station.
Definition industry.h:110
StationList stations_near
NOSAVE: List of nearby stations.
Definition industry.h:125
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
static uint Size()
Get the size of the map.
Definition map_func.h:280
Tindex class_index
Class index of this spec, invalid until class is allocated.
NewGRF supplied spritelayout.
static void Reset(TileIndex tile=INVALID_TILE, bool from_gui=true)
Reset the OrderBackups from GUI/game logic.
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:383
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:33
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:66
bool ShouldStopAtStation(const Vehicle *v, StationID station) const
Check whether the given vehicle should stop at the given station based on this order and the non-stop...
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed).
Definition gfx_type.h:24
static Pool::IterateWrapper< BaseStation > Iterate(size_t from=0)
static T * Create(Targs &&... args)
static Industry * Get(auto index)
static LinkGraph * GetIfValid(auto index)
Road stop specification.
Money GetBuildCost(Price category) const
Get the cost for building a road stop of this type.
std::array< BridgeableTileInfo, 6 > bridgeable_info
Per tile layout bridge information.
CargoGRFFileProps grf_prop
Link to NewGRF.
Money GetClearCost(Price category) const
Get the cost for clearing a road stop of this type.
A Stop for a Road Vehicle.
RoadStop * next
Next stop of the given type at this station.
static RoadStop * GetByTile(TileIndex tile, RoadStopType type)
Find a roadstop at given tile.
Definition roadstop.cpp:253
void MakeDriveThrough()
Join this road stop to another 'base' road stop if possible; fill all necessary data to become an act...
Definition roadstop.cpp:60
void ClearDriveThrough()
Prepare for removal of this stop; update other neighbouring stops if needed.
Definition roadstop.cpp:122
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
uint8_t state
Definition roadveh.h:107
All ships have this type.
Definition ship.h:39
static Station * Create(Targs &&... args)
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Station * GetIfValid(auto index)
static Station * From(BaseStation *st)
static RoadVehicle * From(Vehicle *v)
T * Last()
Get the last vehicle in the chain.
bool HasSpriteGroups() const
Check whether the entity has sprite groups.
Information to handle station action 0 property 24 correctly.
void SetUsed(StringID str)
Mark the given station name as used.
std::bitset< NUM_INDUSTRYTYPES > indtypes
Bit set indicating when an industry type has been found.
std::bitset<(STR_SV_STNAME_FALLBACK - STR_SV_STNAME).base()> used_names
Used default station suffixes.
bool IsAvailable(StringID str) const
Is the given station name available, and not already used?
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Station specification.
std::vector< BridgeableTileInfo > bridgeable_info
Per tile layout bridge information.
uint8_t disallowed_lengths
Bitmask of platform lengths available for the station.
StringID name
Name of this station.
uint8_t disallowed_platforms
Bitmask of number of platforms available for the station.
CargoGRFFileProps grf_prop
Link to NewGRF.
std::vector< TileFlags > tileflags
List of tile flags.
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
EnumBitSet< TileFlag, uint8_t > TileFlags
Bitset of TileFlag elements.
StationCallbackMasks callback_mask
Bitmask of station callbacks that have to be called.
@ NoWires
Tile should NOT contain catenary wires.
@ Pylons
Tile should contain catenary pylons.
@ Blocked
Tile is blocked to vehicles.
StationSpecFlags flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Station data structure.
TileArea GetTileArea(StationType type) const override
Get the tile area for a given station type.
RoadStop * bus_stops
All the road stops.
TileArea ship_station
Tile area the ship 'station' part covers.
IndustryType indtype
Industry type to get the name from.
TileArea docking_station
Tile area the docking tiles cover.
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Industry * industry
NOSAVE: Associated industry for neutral stations. (Rebuilt on load from Industry->st).
void MoveSign(TileIndex new_xy) override
Move the station main coordinate somewhere else.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
TileArea bus_station
Tile area the bus 'station' part covers.
BitmapTileArea catchment_tiles
NOSAVE: Set of individual tiles covered by catchment area.
void RecomputeCatchment(bool no_clear_nearby_lists=false)
Recompute tiles covered in our catchment area.
Definition station.cpp:447
void AfterStationTileSetChange(bool adding, StationType type)
After adding/removing tiles to station, update some station-related stuff.
Airport airport
Tile area the airport covers.
void UpdateVirtCoord() override
Update the virtual coords needed to draw the station sign.
TileArea truck_station
Tile area the truck 'station' part covers.
RoadStop * truck_stops
All the truck stops.
void AddFacility(StationFacility new_facility_bit, TileIndex facil_xy)
Called when new facility is built on the station.
Definition station.cpp:233
uint16_t subst_id
The id of the entity to replace.
Tile description for the 'land area information' tool.
Definition tile_cmd.h:40
uint16_t rail_speed
Speed limit of rail (bridges and track).
Definition tile_cmd.h:53
std::optional< std::string > grf
newGRF used for the tile contents
Definition tile_cmd.h:51
StringID station_name
Type of station within the class.
Definition tile_cmd.h:47
StringID str
Description of the tile.
Definition tile_cmd.h:41
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition tile_cmd.h:45
std::array< Owner, 4 > owner
Name of the owner(s).
Definition tile_cmd.h:43
StringID airport_class
Name of the airport class.
Definition tile_cmd.h:48
StringID airport_name
Name of the airport.
Definition tile_cmd.h:49
uint16_t tram_speed
Speed limit of tram (bridges and track).
Definition tile_cmd.h:57
StringID roadtype
Type of road on the tile.
Definition tile_cmd.h:54
StringID tramtype
Type of tram on the tile.
Definition tile_cmd.h:56
StringID railtype
Type of rail on the tile.
Definition tile_cmd.h:52
uint16_t road_speed
Speed limit of road (bridges and track).
Definition tile_cmd.h:55
std::array< StringID, 4 > owner_type
Type of each owner.
Definition tile_cmd.h:44
StringID airport_tile_name
Name of the airport tile.
Definition tile_cmd.h:50
StringID station_class
Class of station.
Definition tile_cmd.h:46
Tile information, used while rendering the tile.
Definition tile_cmd.h:34
Slope tileh
Slope of the tile.
Definition tile_cmd.h:35
TileIndex tile
Tile index.
Definition tile_cmd.h:36
Town data structure.
Definition town.h:64
CompanyMask statues
which companies have a statue?
Definition town.h:82
TileIndex xy
town center tile
Definition town.h:65
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:80
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:224
CompanyID exclusivity
which company has exclusivity
Definition town.h:87
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:88
Track status of a tile.
Definition track_type.h:105
'Train' is either a loco or a wagon.
Definition train.h:97
Trackdir GetVehicleTrackdir() const override
Get the tracks of the train vehicle.
Vehicle data structure.
Direction GetMovingDirection() const
Get the moving direction of this vehicle chain.
bool IsStoppedInDepot() const
Check whether the vehicle is in the depot and stopped.
bool IsMovingFront() const
Is this vehicle the moving front of the vehicle chain?
TimerGameEconomy::Date date_of_last_service
Last economy date the vehicle had a service at a depot.
virtual void SetDestTile(TileIndex tile)
Set the destination of this vehicle.
VehStates vehstatus
Status.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
virtual TileIndex GetOrderStationLocation(StationID station)
Determine the location for the station where the vehicle goes to next.
Order current_order
The current order (+ status, like: loading).
Vehicle * Next() const
Get the next vehicle of this vehicle.
Vehicle * NextShared() const
Get the next vehicle of the shared vehicle chain.
uint16_t cur_speed
current speed
bool IsFrontEngine() const
Check if the vehicle is a front engine.
TileIndex tile
Current tile index.
TileIndex dest_tile
Heading for this tile.
Owner owner
Which company owns the vehicle?
Representation of a waypoint.
TileArea road_waypoint_area
Tile area the road waypoint part covers.
uint16_t waypoint_flags
Waypoint flags, see WaypointFlags.
void UpdateVirtCoord() override
Update the virtual coords needed to draw the waypoint sign.
@ Source
town/industry is source of subsidised path
@ EnteredStation
The vehicle entered a station.
Definition tile_cmd.h:25
@ CannotEnter
The vehicle cannot enter the tile.
Definition tile_cmd.h:27
void AddProducedCargo(TileIndex tile, CargoArray &produced)
Obtain the produced cargo of a tile.
Definition tile_cmd.h:257
EnumBitSet< VehicleEnterTileState, uint8_t > VehicleEnterTileStates
Bitset of VehicleEnterTileState elements.
Definition tile_cmd.h:31
void AddAcceptedCargo(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
Obtain cargo acceptance of a tile.
Definition tile_cmd.h:245
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:94
std::tuple< Slope, int > GetTileSlopeZ(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.cpp:55
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:135
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:115
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition tile_map.h:198
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition tile_map.h:250
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
TropicZone GetTropicZone(Tile tile)
Get the tropic zone.
Definition tile_map.h:238
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition tile_map.h:262
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Desert
Tile is desert.
Definition tile_type.h:83
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
@ Water
Water tile.
Definition tile_type.h:55
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Industry
Part of an industry.
Definition tile_type.h:57
@ Trees
Tile with one or more trees.
Definition tile_type.h:53
@ House
A house by a town.
Definition tile_type.h:52
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:49
Class for iterating an airport on the map.
Class for iterating an airport layout on the map.
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Type for iterating a sprial tile area.
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
HouseZone GetTownRadiusGroup(const Town *t, TileIndex tile)
Returns the bit corresponding to the town zone of the specified tile.
CommandCost CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlags flags)
Checks whether the local authority allows construction of a new station (rail, road,...
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:292
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:568
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:220
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track Axis::X -> Track::X Axis::Y -> Track::Y Uses the fact that...
Definition track_func.h:62
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:343
Track DiagDirToDiagTrack(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal Track.
Definition track_func.h:419
static constexpr TrackBits TRACK_BIT_3WAY_NE
"Arrow" to the north-east
Definition track_type.h:48
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
static constexpr TrackBits TRACK_BIT_ALL
All possible tracks.
Definition track_type.h:52
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:63
Track
These are used to specify a single track.
Definition track_type.h:19
@ Upper
Track in the upper corner of the tile (north).
Definition track_type.h:23
@ Y
Track along the y-axis (north-west to south-east).
Definition track_type.h:22
@ Left
Track in the left corner of the tile (west).
Definition track_type.h:25
Base for the train class.
bool TryPathReserve(Train *v, bool mark_as_stuck=false, bool first_tile_okay=false)
Try to reserve a path to a safe position.
int GetTrainStopLocation(StationID station_id, TileIndex tile, const Train *moving_front, int *station_ahead, int *station_length)
Get the stop location of (the center) of the front vehicle of a train at a platform of a station.
void FreeTrainTrackReservation(const Train *v)
Free the reserved path in front of a vehicle.
@ Buildings
company buildings - depots, stations, HQ, ...
TransportType
Available types of transport.
@ Water
Transport over water.
@ Rail
Transport by train.
@ Road
Transport by road vehicle.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition vehicle.cpp:559
@ TrainSlowing
Train is slowing down.
Functions related to vehicles.
@ Ship
Ship vehicle type.
@ Invalid
Non-existing type of vehicle.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
Functions and type for generating vehicle lists.
void FindVehiclesWithOrder(VehiclePredicate veh_pred, OrderPredicate ord_pred, VehicleFunc veh_func)
Find vehicles matching an order.
void OffsetGroundSprite(int x, int y)
Called when a foundation has been drawn for the current tile.
Definition viewport.cpp:606
void SetViewportStationRect(const Station *st, bool sel)
Select or deselect station for rectangle area highlight.
void StartSpriteCombine()
Starts a block of sprites, which are "combined" into a single bounding box.
Definition viewport.cpp:766
void AddSortableSpriteToDraw(SpriteID image, PaletteID pal, int x, int y, int z, const SpriteBounds &bounds, bool transparent, const SubSprite *sub)
Draw a (transparent) sprite at given coordinates with a given bounding box.
Definition viewport.cpp:665
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:776
void DrawGroundSprite(SpriteID image, PaletteID pal, const SubSprite *sub, int extra_offs_x, int extra_offs_y)
Draws a ground sprite for the current tile.
Definition viewport.cpp:580
Functions related to (drawing on) viewports.
static const int TILE_HEIGHT_STEP
One Z unit tile height difference is displayed as 50m.
Declarations for accessing the k-d tree of viewports.
Functions related to water management.
void TileLoop_Water(TileIndex tile)
Tile callback function signature for running periodic tile updates.
void CheckForDockingTile(TileIndex t)
Mark the supplied tile as a docking tile if it is suitable for docking.
bool IsPossibleDockingTile(Tile t)
Check whether it is feasible that the given tile could be a docking tile.
bool HasTileWaterGround(Tile t)
Checks whether the tile has water at the ground.
Definition water_map.h:356
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition water_map.h:140
WaterClass
classes of water (for WaterTileType::Clear water tile type).
Definition water_map.h:41
@ Invalid
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:45
@ Canal
Canal.
Definition water_map.h:43
@ Sea
Sea.
Definition water_map.h:42
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition water_map.h:105
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:116
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition water_map.h:378
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:367
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:151
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition water_map.h:194
Base of waypoints.
@ WPF_ROAD
This is a road waypoint.
CommandCost RemoveBuoy(TileIndex tile, DoCommandFlags flags)
Remove a buoy.
Command definitions related to waypoints.
Functions related to waypoints.
void ShowWaypointWindow(const Waypoint *wp)
Show the window for the given waypoint.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
Definition window.cpp:3271
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Entry point for OpenTTD to YAPF's cache.
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
@ Station
station encountered (could be a target next time)
Definition yapf_type.hpp:26