OpenTTD Source 20260604-master-ga892d8e848
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_map.h"
14#include "vehiclelist_func.h"
15#include "viewport_func.h"
16#include "viewport_kdtree.h"
17#include "command_func.h"
18#include "town.h"
19#include "news_func.h"
20#include "train.h"
21#include "ship.h"
22#include "roadveh.h"
23#include "industry.h"
24#include "newgrf_cargo.h"
25#include "newgrf_debug.h"
26#include "newgrf_station.h"
27#include "newgrf_canal.h" /* For the buoy */
29#include "road_internal.h" /* For drawing catenary/checking road removal */
30#include "autoslope.h"
31#include "water.h"
32#include "tilehighlight_func.h"
33#include "strings_func.h"
34#include "clear_func.h"
36#include "vehicle_func.h"
37#include "string_func.h"
38#include "animated_tile_func.h"
39#include "elrail_func.h"
40#include "station_base.h"
41#include "station_func.h"
42#include "station_kdtree.h"
43#include "roadstop_base.h"
44#include "newgrf_railtype.h"
45#include "newgrf_roadtype.h"
46#include "waypoint_base.h"
47#include "waypoint_func.h"
48#include "pbs.h"
49#include "debug.h"
50#include "core/random_func.hpp"
52#include "company_base.h"
54#include "newgrf_airporttiles.h"
55#include "order_backup.h"
56#include "newgrf_house.h"
57#include "company_gui.h"
59#include "linkgraph/refresh.h"
60#include "tunnelbridge_map.h"
61#include "station_cmd.h"
62#include "waypoint_cmd.h"
63#include "landscape_cmd.h"
64#include "rail_cmd.h"
65#include "newgrf_roadstop.h"
66#include "timer/timer.h"
70#include "cheat_type.h"
71#include "road_func.h"
72#include "station_layout_type.h"
73
75#include "widgets/misc_widget.h"
76
77#include "table/strings.h"
78#include "table/station_land.h"
79
80#include <bitset>
81
82#include "safeguards.h"
83
89/* static */ const FlowStat::SharesMap FlowStat::empty_sharesmap;
90
98{
99 assert(IsTileType(t, TileType::Station));
100
101 /* If the tile isn't an airport there's no chance it's a hangar. */
102 if (!IsAirport(t)) return false;
103
104 const Station *st = Station::GetByTile(t);
105 const AirportSpec *as = st->airport.GetSpec();
106
107 for (const auto &depot : as->depots) {
108 if (st->airport.GetRotatedTileFromOffset(depot.ti) == TileIndex(t)) return true;
109 }
110
111 return false;
112}
113
123template <class T, class F>
124CommandCost GetStationAround(TileArea ta, StationID closest_station, CompanyID company, T **st, F filter)
125{
126 ta.Expand(1);
127
128 /* check around to see if there are any stations there owned by the company */
129 for (TileIndex tile_cur : ta) {
130 if (IsTileType(tile_cur, TileType::Station)) {
131 StationID t = GetStationIndex(tile_cur);
132 if (!T::IsValidID(t) || T::Get(t)->owner != company || !filter(T::Get(t))) continue;
133 if (closest_station == StationID::Invalid()) {
134 closest_station = t;
135 } else if (closest_station != t) {
136 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
137 }
138 }
139 }
140 *st = (closest_station == StationID::Invalid()) ? nullptr : T::Get(closest_station);
141 return CommandCost();
142}
143
149typedef bool (*CMSAMatcher)(TileIndex tile);
150
158{
159 int num = 0;
160
161 for (int dx = -3; dx <= 3; dx++) {
162 for (int dy = -3; dy <= 3; dy++) {
163 TileIndex t = TileAddWrap(tile, dx, dy);
164 if (t != INVALID_TILE && cmp(t)) num++;
165 }
166 }
167
168 return num;
169}
170
176static bool CMSAMine(TileIndex tile)
177{
178 /* No industry */
179 if (!IsTileType(tile, TileType::Industry)) return false;
180
181 const Industry *ind = Industry::GetByTile(tile);
182
183 /* No extractive industry */
185
186 for (const auto &p : ind->produced) {
187 /* The industry extracts something non-liquid, i.e. no oil or plastic, so it is a mine.
188 * Also the production of passengers and mail is ignored. */
189 if (IsValidCargoType(p.cargo) &&
190 !CargoSpec::Get(p.cargo)->classes.Any({CargoClass::Liquid, CargoClass::Passengers, CargoClass::Mail})) {
191 return true;
192 }
193 }
194
195 return false;
196}
197
203static bool CMSAWater(TileIndex tile)
204{
205 return IsTileType(tile, TileType::Water) && IsWater(tile);
206}
207
213static bool CMSATree(TileIndex tile)
214{
215 return IsTileType(tile, TileType::Trees);
216}
217
227
230 std::bitset<STR_SV_STNAME_FALLBACK - STR_SV_STNAME> used_names;
231 std::bitset<NUM_INDUSTRYTYPES> indtypes;
232
238 bool IsAvailable(StringID str) const
239 {
240 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
241 return !this->used_names.test(str - STR_SV_STNAME);
242 }
243
249 {
250 assert(IsInsideMM(str, STR_SV_STNAME, STR_SV_STNAME_FALLBACK));
251 this->used_names.set(str - STR_SV_STNAME);
252 }
253};
254
264{
265 const Town *t = st->town;
266
268
269 for (const Station *s : Station::Iterate()) {
270 if (s != st && s->town == t) {
271 if (s->indtype != IT_INVALID) {
272 sni.indtypes[s->indtype] = true;
273 StringID name = GetIndustrySpec(s->indtype)->station_name;
274 if (name != STR_UNDEFINED) {
275 /* Filter for other industrytypes with the same name */
276 for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
277 const IndustrySpec *indsp = GetIndustrySpec(it);
278 if (indsp->enabled && indsp->station_name == name) sni.indtypes[it] = true;
279 }
280 }
281 continue;
282 }
283 if (IsInsideMM(s->string_id, STR_SV_STNAME, STR_SV_STNAME_FALLBACK)) {
284 auto str = s->string_id;
285 if (str == STR_SV_STNAME_FOREST) str = STR_SV_STNAME_WOODS;
286 sni.SetUsed(str);
287 }
288 }
289 }
290
291 for (auto indtile : SpiralTileSequence(tile, 7)) {
292 if (!IsTileType(indtile, TileType::Industry)) continue;
293
294 /* If the station name is undefined it means that it doesn't name a station */
295 IndustryType indtype = GetIndustryType(indtile);
296 const IndustrySpec *indsp = GetIndustrySpec(indtype);
297 if (indsp->station_name == STR_UNDEFINED) continue;
298
299 /* In all cases if an industry that provides a name is found two of
300 * the standard names will be disabled. */
301 sni.SetUsed(STR_SV_STNAME_OILFIELD);
302 sni.SetUsed(STR_SV_STNAME_MINES);
303 if (sni.indtypes[indtype]) continue;
304
305 /* STR_NULL means it only disables oil rig/mines */
306 if (indsp->station_name != STR_NULL) {
307 st->indtype = indtype;
308 return STR_SV_STNAME_FALLBACK;
309 }
310 break;
311 }
312
313 /* check default names
314 * Oil rigs/mines name could be marked not free by looking for a near by industry. */
315 switch (name_class) {
317 if (sni.IsAvailable(STR_SV_STNAME_AIRPORT)) return STR_SV_STNAME_AIRPORT;
318 break;
320 if (sni.IsAvailable(STR_SV_STNAME_OILFIELD)) return STR_SV_STNAME_OILFIELD;
321 break;
323 if (sni.IsAvailable(STR_SV_STNAME_DOCKS)) return STR_SV_STNAME_DOCKS;
324 break;
326 if (sni.IsAvailable(STR_SV_STNAME_HELIPORT)) return STR_SV_STNAME_HELIPORT;
327 break;
328 default:
329 break;
330 };
331
332 /* check mine? */
333 if (sni.IsAvailable(STR_SV_STNAME_MINES)) {
334 if (CountMapSquareAround(tile, CMSAMine) >= 2) {
335 return STR_SV_STNAME_MINES;
336 }
337 }
338
339 /* check close enough to town to get central as name? */
340 if (DistanceMax(tile, t->xy) < 8) {
341 if (sni.IsAvailable(STR_SV_STNAME)) return STR_SV_STNAME;
342 if (sni.IsAvailable(STR_SV_STNAME_CENTRAL)) return STR_SV_STNAME_CENTRAL;
343 }
344
345 /* Check lakeside */
346 if (sni.IsAvailable(STR_SV_STNAME_LAKESIDE) &&
347 DistanceFromEdge(tile) < 20 &&
348 CountMapSquareAround(tile, CMSAWater) >= 5) {
349 return STR_SV_STNAME_LAKESIDE;
350 }
351
352 /* Check woods */
353 if (sni.IsAvailable(STR_SV_STNAME_WOODS) && (
354 CountMapSquareAround(tile, CMSATree) >= 8 ||
356 ) {
357 return _settings_game.game_creation.landscape == LandscapeType::Tropic ? STR_SV_STNAME_FOREST : STR_SV_STNAME_WOODS;
358 }
359
360 /* check elevation compared to town */
361 int z = GetTileZ(tile);
362 int z2 = GetTileZ(t->xy);
363 if (z < z2) {
364 if (sni.IsAvailable(STR_SV_STNAME_VALLEY)) return STR_SV_STNAME_VALLEY;
365 } else if (z > z2) {
366 if (sni.IsAvailable(STR_SV_STNAME_HEIGHTS)) return STR_SV_STNAME_HEIGHTS;
367 }
368
369 /* check direction compared to town */
370 if (TileX(tile) < TileX(t->xy)) {
371 sni.SetUsed(STR_SV_STNAME_SOUTH);
372 sni.SetUsed(STR_SV_STNAME_WEST);
373 } else {
374 sni.SetUsed(STR_SV_STNAME_NORTH);
375 sni.SetUsed(STR_SV_STNAME_EAST);
376 }
377 if (TileY(tile) < TileY(t->xy)) {
378 sni.SetUsed(STR_SV_STNAME_SOUTH);
379 sni.SetUsed(STR_SV_STNAME_EAST);
380 } else {
381 sni.SetUsed(STR_SV_STNAME_NORTH);
382 sni.SetUsed(STR_SV_STNAME_WEST);
383 }
384
386 static const StringID fallback_names[] = {
387 STR_SV_STNAME_NORTH,
388 STR_SV_STNAME_SOUTH,
389 STR_SV_STNAME_EAST,
390 STR_SV_STNAME_WEST,
391 STR_SV_STNAME_TRANSFER,
392 STR_SV_STNAME_HALT,
393 STR_SV_STNAME_EXCHANGE,
394 STR_SV_STNAME_ANNEXE,
395 STR_SV_STNAME_SIDINGS,
396 STR_SV_STNAME_BRANCH,
397 STR_SV_STNAME_UPPER,
398 STR_SV_STNAME_LOWER,
399 };
400 for (auto str : fallback_names) {
401 if (sni.IsAvailable(str)) return str;
402 }
403 return STR_SV_STNAME_FALLBACK;
404}
405
412{
413 uint threshold = 8;
414
415 Station *best_station = nullptr;
416 ForAllStationsRadius(tile, threshold, [&](Station *st) {
417 if (!st->IsInUse() && st->owner == _current_company) {
418 uint cur_dist = DistanceManhattan(tile, st->xy);
419
420 if (cur_dist < threshold) {
421 threshold = cur_dist;
422 best_station = st;
423 } else if (cur_dist == threshold && best_station != nullptr) {
424 /* In case of a tie, lowest station ID wins */
425 if (st->index < best_station->index) best_station = st;
426 }
427 }
428 });
429
430 return best_station;
431}
432
433
435{
436 switch (type) {
437 case StationType::Rail: return this->train_station;
438 case StationType::Airport: return this->airport;
439 case StationType::Truck: return this->truck_station;
440 case StationType::Bus: return this->bus_station;
442 case StationType::Oilrig: return this->docking_station;
443 default: NOT_REACHED();
444 }
445}
446
451{
452 Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
453
454 pt.y -= 32 * ZOOM_BASE;
455 if (this->facilities.Test(StationFacility::Airport) && this->airport.type == AT_OILRIG) pt.y -= 16 * ZOOM_BASE;
456
457 if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeStation(this->index));
458
459 this->sign.UpdatePosition(pt.x, pt.y, GetString(STR_VIEWPORT_STATION, this->index, this->facilities), GetString(STR_STATION_NAME, this->index, this->facilities));
460
461 _viewport_sign_kdtree.Insert(ViewportSignKdtreeItem::MakeStation(this->index));
462
463 SetWindowDirty(WindowClass::StationView, this->index);
464}
465
471{
472 if (this->xy == new_xy) return;
473
474 _station_kdtree.Remove(this->index);
475
476 this->BaseStation::MoveSign(new_xy);
477
478 _station_kdtree.Insert(this->index);
479}
480
483{
484 for (BaseStation *st : BaseStation::Iterate()) {
485 st->UpdateVirtCoord();
486 }
487}
488
489void BaseStation::FillCachedName() const
490{
491 auto tmp_params = MakeParameters(this->index);
492 this->cached_name = GetStringWithArgs(Waypoint::IsExpected(this) ? STR_WAYPOINT_NAME : STR_STATION_NAME, tmp_params);
493}
494
495void ClearAllStationCachedNames()
496{
497 for (BaseStation *st : BaseStation::Iterate()) {
498 st->cached_name.clear();
499 }
500}
501
507CargoTypes GetAcceptanceMask(const Station *st)
508{
509 CargoTypes mask{};
510
511 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
512 if (it->status.Test(GoodsEntry::State::Acceptance)) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
513 }
514 return mask;
515}
516
522CargoTypes GetCargoWaitingMask(const Station *st)
523{
524 CargoTypes mask{};
525
526 for (auto it = std::begin(st->goods); it != std::end(st->goods); ++it) {
527 if (it->TotalCount() > 0) mask.Set(static_cast<CargoType>(std::distance(std::begin(st->goods), it)));
528 }
529 return mask;
530}
531
538static void ShowRejectOrAcceptNews(const Station *st, CargoTypes cargoes, bool reject)
539{
540 StringID msg = reject ? STR_NEWS_STATION_NO_LONGER_ACCEPTS_CARGO_LIST : STR_NEWS_STATION_NOW_ACCEPTS_CARGO_LIST;
542}
543
552CargoArray GetProductionAroundTiles(TileIndex north_tile, int w, int h, int rad)
553{
554 CargoArray produced{};
555 FlatSet<IndustryID> industries;
556 TileArea ta = TileArea(north_tile, w, h).Expand(rad);
557
558 /* Loop over all tiles to get the produced cargo of
559 * everything except industries */
560 for (TileIndex tile : ta) {
561 if (IsTileType(tile, TileType::Industry)) industries.insert(GetIndustryIndex(tile));
562 AddProducedCargo(tile, produced);
563 }
564
565 /* Loop over the seen industries. They produce cargo for
566 * anything that is within 'rad' of any one of their tiles.
567 */
568 for (IndustryID industry : industries) {
569 const Industry *i = Industry::Get(industry);
570 /* Skip industry with neutral station */
571 if (i->neutral_station != nullptr && !_settings_game.station.serve_neutral_industries) continue;
572
573 for (const auto &p : i->produced) {
574 if (IsValidCargoType(p.cargo)) produced[p.cargo]++;
575 }
576 }
577
578 return produced;
579}
580
589std::pair<CargoArray, CargoTypes> GetAcceptanceAroundTiles(TileIndex center_tile, int w, int h, int rad)
590{
591 CargoArray acceptance{};
592 CargoTypes always_accepted{};
593
594 TileArea ta = TileArea(center_tile, w, h).Expand(rad);
595
596 for (TileIndex tile : ta) {
597 /* Ignore industry if it has a neutral station. */
598 if (!_settings_game.station.serve_neutral_industries && IsTileType(tile, TileType::Industry) && Industry::GetByTile(tile)->neutral_station != nullptr) continue;
599
600 AddAcceptedCargo(tile, acceptance, always_accepted);
601 }
602
603 return {acceptance, always_accepted};
604}
605
611static std::pair<CargoArray, CargoTypes> GetAcceptanceAroundStation(const Station *st)
612{
613 CargoArray acceptance{};
614 CargoTypes always_accepted{};
615
617 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
618 AddAcceptedCargo(tile, acceptance, always_accepted);
619 }
620
621 return {acceptance, always_accepted};
622}
623
629void UpdateStationAcceptance(Station *st, bool show_msg)
630{
631 /* old accepted goods types */
632 CargoTypes old_acc = GetAcceptanceMask(st);
633
634 /* And retrieve the acceptance. */
635 CargoArray acceptance{};
636 if (!st->rect.IsEmpty()) {
637 std::tie(acceptance, st->always_accepted) = GetAcceptanceAroundStation(st);
638 }
639
640 /* Adjust in case our station only accepts fewer kinds of goods */
641 for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) {
642 uint amt = acceptance[cargo];
643
644 /* Make sure the station can accept the goods type. */
645 bool is_passengers = IsCargoInClass(cargo, CargoClass::Passengers);
646 if ((!is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::TruckStop, StationFacility::Airport, StationFacility::Dock})) ||
647 (is_passengers && !st->facilities.Any({StationFacility::Train, StationFacility::BusStop, StationFacility::Airport, StationFacility::Dock}))) {
648 amt = 0;
649 }
650
651 GoodsEntry &ge = st->goods[cargo];
654 (*LinkGraph::Get(ge.link_graph))[ge.node].SetDemand(amt / 8);
655 }
656 }
657
658 /* Only show a message in case the acceptance was actually changed. */
659 CargoTypes new_acc = GetAcceptanceMask(st);
660 if (old_acc == new_acc) return;
661
662 /* show a message to report that the acceptance was changed? */
663 if (show_msg && st->owner == _local_company && st->IsInUse()) {
664 /* Combine old and new masks to get changes */
665 CargoTypes accepts = new_acc & CargoTypes{old_acc}.Flip();
666 CargoTypes rejects = CargoTypes{new_acc}.Flip() & old_acc;
667
668 /* Show news message if there are any changes */
669 if (accepts.Any()) ShowRejectOrAcceptNews(st, accepts, false);
670 if (rejects.Any()) ShowRejectOrAcceptNews(st, rejects, true);
671 }
672
673 /* redraw the station view since acceptance changed */
674 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_ACCEPT_RATING_LIST);
675}
676
677static void UpdateStationSignCoord(BaseStation *st)
678{
679 const StationRect *r = &st->rect;
680
681 if (r->IsEmpty()) return; // no tiles belong to this station
682
683 /* clamp sign coord to be inside the station rect */
684 TileIndex new_xy = TileXY(ClampU(TileX(st->xy), r->left, r->right), ClampU(TileY(st->xy), r->top, r->bottom));
685 st->MoveSign(new_xy);
686
687 if (!Station::IsExpected(st)) return;
688 Station *full_station = Station::From(st);
689 for (const GoodsEntry &ge : full_station->goods) {
690 LinkGraphID lg = ge.link_graph;
691 if (!LinkGraph::IsValidID(lg)) continue;
692 (*LinkGraph::Get(lg))[ge.node].UpdateLocation(st->xy);
693 }
694}
695
705static CommandCost BuildStationPart(Station **st, DoCommandFlags flags, bool reuse, TileArea area, StationNaming name_class)
706{
707 /* Find a deleted station close to us */
708 if (*st == nullptr && reuse) *st = GetClosestDeletedStation(area.tile);
709
710 if (*st != nullptr) {
711 if ((*st)->owner != _current_company) {
712 return CommandCost(CMD_ERROR);
713 }
714
715 CommandCost ret = (*st)->rect.BeforeAddRect(area.tile, area.w, area.h, StationRect::ADD_TEST);
716 if (ret.Failed()) return ret;
717 } else {
718 /* allocate and initialize new station */
719 if (!Station::CanAllocateItem()) return CommandCost(STR_ERROR_TOO_MANY_STATIONS_LOADING);
720
721 if (flags.Test(DoCommandFlag::Execute)) {
722 *st = Station::Create(area.tile);
723 _station_kdtree.Insert((*st)->index);
724
725 (*st)->town = ClosestTownFromTile(area.tile, UINT_MAX);
726 (*st)->string_id = GenerateStationName(*st, area.tile, name_class);
727
729 (*st)->town->have_ratings.Set(_current_company);
730 }
731 }
732 }
733 return CommandCost();
734}
735
743{
744 if (!st->IsInUse()) {
745 st->delete_ctr = 0;
746 InvalidateWindowData(WindowClass::StationList, st->owner, 0);
747 }
748 /* station remains but it probably lost some parts - station sign should stay in the station boundaries */
749 UpdateStationSignCoord(st);
750}
751
758{
759 this->UpdateVirtCoord();
761
762 if (adding) {
763 this->RecomputeCatchment();
764 MarkCatchmentTilesDirty();
765 InvalidateWindowData(WindowClass::StationList, this->owner, 0);
766 } else {
767 MarkCatchmentTilesDirty();
768 }
769
770 switch (type) {
772 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_TRAINS);
773 break;
775 break;
777 case StationType::Bus:
778 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_ROADVEHS);
779 break;
781 SetWindowWidgetDirty(WindowClass::StationView, this->index, WID_SV_SHIPS);
782 break;
783 default: NOT_REACHED();
784 }
785
786 if (adding) {
787 UpdateStationAcceptance(this, false);
788 InvalidateWindowData(WindowClass::JoinStation, 0, 0);
789 } else {
791 this->RecomputeCatchment();
792 }
793
794}
795
796CommandCost ClearTile_Station(TileIndex tile, DoCommandFlags flags);
797
807CommandCost CheckBuildableTile(TileIndex tile, DiagDirections invalid_dirs, int &allowed_z, bool allow_steep, bool check_bridge = true)
808{
809 if (check_bridge && IsBridgeAbove(tile)) {
810 return CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
811 }
812
814 if (ret.Failed()) return ret;
815
816 auto [tileh, z] = GetTileSlopeZ(tile);
817
818 /* Prohibit building if
819 * 1) The tile is "steep" (i.e. stretches two height levels).
820 * 2) The tile is non-flat and the build_on_slopes switch is disabled.
821 */
822 if ((!allow_steep && IsSteepSlope(tileh)) ||
823 ((!_settings_game.construction.build_on_slopes) && tileh != SLOPE_FLAT)) {
824 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
825 }
826
828 int flat_z = z + GetSlopeMaxZ(tileh);
829 if (tileh != SLOPE_FLAT) {
830 /* Forbid building if the tile faces a slope in a invalid direction. */
831 for (DiagDirection dir = DiagDirection::Begin; dir != DiagDirection::End; dir++) {
832 if (invalid_dirs.Test(dir) && !CanBuildDepotByTileh(dir, tileh)) {
833 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
834 }
835 }
837 }
838
839 /* The level of this tile must be equal to allowed_z. */
840 if (allowed_z < 0) {
841 /* First tile. */
842 allowed_z = flat_z;
843 } else if (allowed_z != flat_z) {
844 return CommandCost(STR_ERROR_FLAT_LAND_REQUIRED);
845 }
846
847 return cost;
848}
849
856static CommandCost CheckFlatLandAirport(AirportTileTableIterator tile_iter, DoCommandFlags flags)
857{
859 int allowed_z = -1;
860
861 for (; tile_iter != INVALID_TILE; ++tile_iter) {
862 CommandCost ret = CheckBuildableTile(tile_iter, {}, allowed_z, true);
863 if (ret.Failed()) return ret;
864 cost.AddCost(ret.GetCost());
865
866 ret = Command<Commands::LandscapeClear>::Do(flags, tile_iter);
867 if (ret.Failed()) return ret;
868 cost.AddCost(ret.GetCost());
869 }
870
871 return cost;
872}
873
880{
882 STR_ERROR_BRIDGE_TOO_LOW_FOR_STATION, // Rail
883 INVALID_STRING_ID, // Airport
884 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Truck
885 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROADSTOP, // Bus
886 INVALID_STRING_ID, // Oilrig
887 STR_ERROR_BRIDGE_TOO_LOW_FOR_DOCK, // Dock
888 STR_ERROR_BRIDGE_TOO_LOW_FOR_BUOY, // Buoy
889 STR_ERROR_BRIDGE_TOO_LOW_FOR_RAIL_WAYPOINT, // RailWaypoint
890 STR_ERROR_BRIDGE_TOO_LOW_FOR_ROAD_WAYPOINT, // RoadWaypoint
891 };
892 return too_low_msgs[type];
893};
894
905static CommandCost IsStationBridgeAboveOk(TileIndex tile, std::span<const BridgeableTileInfo> bridgeable_info, StationType type, StationGfx layout, int bridge_height, StringID disallowed_msg = INVALID_STRING_ID)
906{
907 int height = layout < std::size(bridgeable_info) ? bridgeable_info[layout].height : 0;
908
909 if (height == 0) {
910 if (disallowed_msg != INVALID_STRING_ID) return CommandCost{disallowed_msg};
911 /* Get normal error message associated with clearing the tile. */
912 return Command<Commands::LandscapeClear>::Do(DoCommandFlag::Auto, tile);
913 }
914 if (GetTileMaxZ(tile) + height > bridge_height) {
915 int height_diff = (GetTileMaxZ(tile) + height - bridge_height) * TILE_HEIGHT_STEP;
917 }
918
919 return CommandCost{};
920}
921
927static std::span<const BridgeableTileInfo> GetStationBridgeableTileInfo(StationType type)
928{
929 return _station_bridgeable_info[type];
930}
931
941{
942 if (!IsBridgeAbove(tile)) return CommandCost();
943
944 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
945 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
946 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
947}
948
958{
959 if (!IsBridgeAbove(tile)) return CommandCost();
960
961 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
962 auto bridgeable_info = spec == nullptr ? GetStationBridgeableTileInfo(type) : spec->bridgeable_info;
963 return IsStationBridgeAboveOk(tile, bridgeable_info, type, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
964}
965
973{
974 if (!IsBridgeAbove(tile)) return CommandCost();
975
976 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
977 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Dock);
978 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Dock, layout, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
979}
980
987{
988 if (!IsBridgeAbove(tile)) return CommandCost();
989
990 TileIndex rampsouth = GetSouthernBridgeEnd(tile);
991 auto bridgeable_info = GetStationBridgeableTileInfo(StationType::Buoy);
992 return IsStationBridgeAboveOk(tile, bridgeable_info, StationType::Buoy, 0, GetBridgeHeight(rampsouth), STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
993}
994
1011static 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)
1012{
1014 DiagDirections invalid_dirs = AxisToDiagDirs(axis);
1015
1016 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1017 bool slope_cb = statspec != nullptr && statspec->callback_mask.Test(StationCallbackMask::SlopeCheck);
1018
1019 CommandCost ret = CheckBuildableTile(tile_cur, invalid_dirs, allowed_z, false, false);
1020 if (ret.Failed()) return ret;
1021 cost.AddCost(ret.GetCost());
1022
1023 if (slope_cb) {
1024 /* Do slope check if requested. */
1025 ret = PerformStationTileSlopeCheck(north_tile, tile_cur, statspec, axis, plat_len, numtracks);
1026 if (ret.Failed()) return ret;
1027 }
1028
1029 /* if station is set, then we have special handling to allow building on top of already existing stations.
1030 * so station points to StationID::Invalid() if we can build on any station.
1031 * Or it points to a station if we're only allowed to build on exactly that station. */
1032 if (station != nullptr && IsTileType(tile_cur, TileType::Station)) {
1033 if (!IsRailStation(tile_cur)) {
1034 return ClearTile_Station(tile_cur, DoCommandFlag::Auto); // get error message
1035 } else {
1036 StationID st = GetStationIndex(tile_cur);
1037 if (*station == StationID::Invalid()) {
1038 *station = st;
1039 } else if (*station != st) {
1040 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1041 }
1042 }
1043 } else {
1044 /* If we are building a station with a valid railtype, we may be able to overbuild an existing rail tile. */
1045 if (rt != INVALID_RAILTYPE && IsPlainRailTile(tile_cur)) {
1046 /* Don't overbuild signals. */
1047 if (HasSignals(tile_cur)) return CommandCost(STR_ERROR_MUST_REMOVE_SIGNALS_FIRST);
1048
1049 /* The current rail type must have power on the to-be-built type (e.g. convert normal rail to electrified rail). */
1050 if (HasPowerOnRail(GetRailType(tile_cur), rt)) {
1051 /* The existing track must align with the desired station axis. */
1052 Track track = AxisToTrack(axis);
1053 if (GetTrackBits(tile_cur) == TrackToTrackBits(track)) {
1054 /* Check for trains having a reservation for this tile. */
1055 if (HasBit(GetRailReservationTrackBits(tile_cur), track)) {
1056 Train *v = GetTrainForReservation(tile_cur, track);
1057 if (v != nullptr) {
1058 affected_vehicles.push_back(v);
1059 }
1060 }
1061 ret = Command<Commands::RemoveRail>::Do(flags, tile_cur, track);
1062 if (ret.Failed()) return ret;
1063 cost.AddCost(ret.GetCost());
1064 /* With DoCommandFlags{flags}.Reset(DoCommandFlag::Execute) CmdLandscapeClear would fail since the rail still exists */
1065 return cost;
1066 }
1067 }
1068 }
1069 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
1070 if (ret.Failed()) return ret;
1071 cost.AddCost(ret.GetCost());
1072 }
1073
1074 return cost;
1075}
1076
1091static 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)
1092{
1094
1095 CommandCost ret = CheckBuildableTile(cur_tile, invalid_dirs, allowed_z, !is_drive_through, false);
1096 if (ret.Failed()) return ret;
1097 cost.AddCost(ret.GetCost());
1098
1099 ret = IsRoadStationBridgeAboveOk(cur_tile, spec, station_type, is_drive_through ? GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET + to_underlying(axis) : FindFirstBit(invalid_dirs.base()));
1100 if (ret.Failed()) return ret;
1101
1102 /* If station is set, then we have special handling to allow building on top of already existing stations.
1103 * Station points to StationID::Invalid() if we can build on any station.
1104 * Or it points to a station if we're only allowed to build on exactly that station. */
1105 if (station != nullptr && IsTileType(cur_tile, TileType::Station)) {
1106 if (!IsAnyRoadStop(cur_tile)) {
1107 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1108 } else {
1109 if (station_type != GetStationType(cur_tile) ||
1110 is_drive_through != IsDriveThroughStopTile(cur_tile)) {
1111 return ClearTile_Station(cur_tile, DoCommandFlag::Auto); // Get error message.
1112 }
1113 /* Drive-through station in the wrong direction. */
1114 if (is_drive_through && IsDriveThroughStopTile(cur_tile) && GetDriveThroughStopAxis(cur_tile) != axis) {
1115 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1116 }
1117 StationID st = GetStationIndex(cur_tile);
1118 if (*station == StationID::Invalid()) {
1119 *station = st;
1120 } else if (*station != st) {
1121 return CommandCost(STR_ERROR_ADJOINS_MORE_THAN_ONE_EXISTING);
1122 }
1123 }
1124 } else {
1125 bool build_over_road = is_drive_through && IsNormalRoadTile(cur_tile);
1126 /* Road bits in the wrong direction. */
1127 RoadBits rb = IsNormalRoadTile(cur_tile) ? GetAllRoadBits(cur_tile) : RoadBits{};
1128 if (build_over_road && rb.Any(AxisToRoadBits(OtherAxis(axis)))) {
1129 /* Someone was pedantic and *NEEDED* three fracking different error messages. */
1130 switch (rb.Count()) {
1131 case 1:
1132 return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1133
1134 case 2:
1135 if (rb == ROAD_X || rb == ROAD_Y) return CommandCost(STR_ERROR_DRIVE_THROUGH_DIRECTION);
1136 return CommandCost(STR_ERROR_DRIVE_THROUGH_CORNER);
1137
1138 default: // 3 or 4
1139 return CommandCost(STR_ERROR_DRIVE_THROUGH_JUNCTION);
1140 }
1141 }
1142
1143 if (build_over_road) {
1144 /* There is a road, check if we can build road+tram stop over it. */
1145 RoadType road_rt = GetRoadType(cur_tile, RoadTramType::Road);
1146 if (road_rt != INVALID_ROADTYPE) {
1147 Owner road_owner = GetRoadOwner(cur_tile, RoadTramType::Road);
1148 if (road_owner == OWNER_TOWN) {
1149 if (!_settings_game.construction.road_stop_on_town_road) return CommandCost(STR_ERROR_DRIVE_THROUGH_ON_TOWN_ROAD);
1150 } else if (!_settings_game.construction.road_stop_on_competitor_road && road_owner != OWNER_NONE) {
1151 ret = CheckOwnership(road_owner);
1152 if (ret.Failed()) return ret;
1153 }
1154 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Road).Count();
1155
1156 if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt) && !HasPowerOnRoad(rt, road_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1157
1158 if (GetDisallowedRoadDirections(cur_tile).Any() && road_owner != OWNER_TOWN && road_owner != OWNER_NONE) {
1159 ret = CheckOwnership(road_owner);
1160 if (ret.Failed()) return ret;
1161 }
1162
1163 cost.AddCost(RoadBuildCost(road_rt) * (2 - num_pieces));
1164 } else if (rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt)) {
1165 cost.AddCost(RoadBuildCost(rt) * 2);
1166 }
1167
1168 /* There is a tram, check if we can build road+tram stop over it. */
1169 RoadType tram_rt = GetRoadType(cur_tile, RoadTramType::Tram);
1170 if (tram_rt != INVALID_ROADTYPE) {
1171 Owner tram_owner = GetRoadOwner(cur_tile, RoadTramType::Tram);
1172 if (Company::IsValidID(tram_owner) &&
1173 (!_settings_game.construction.road_stop_on_competitor_road ||
1174 /* Disallow breaking end-of-line of someone else
1175 * so trams can still reverse on this tile. */
1176 GetRoadBits(cur_tile, RoadTramType::Tram).Count() == 1)) {
1177 ret = CheckOwnership(tram_owner);
1178 if (ret.Failed()) return ret;
1179 }
1180 uint num_pieces = GetRoadBits(cur_tile, RoadTramType::Tram).Count();
1181
1182 if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt) && !HasPowerOnRoad(rt, tram_rt)) return CommandCost(STR_ERROR_NO_SUITABLE_ROAD);
1183
1184 cost.AddCost(RoadBuildCost(tram_rt) * (2 - num_pieces));
1185 } else if (rt != INVALID_ROADTYPE && RoadTypeIsTram(rt)) {
1186 cost.AddCost(RoadBuildCost(rt) * 2);
1187 }
1188 } else if (rt == INVALID_ROADTYPE) {
1189 return CommandCost(STR_ERROR_THERE_IS_NO_ROAD);
1190 } else {
1191 ret = Command<Commands::LandscapeClear>::Do(flags, cur_tile);
1192 if (ret.Failed()) return ret;
1193 cost.AddCost(ret.GetCost());
1194 cost.AddCost(RoadBuildCost(rt) * 2);
1195 }
1196 }
1197
1198 return cost;
1199}
1200
1208{
1209 TileArea cur_ta = st->train_station;
1210
1211 /* determine new size of train station region.. */
1212 int x = std::min(TileX(cur_ta.tile), TileX(new_ta.tile));
1213 int y = std::min(TileY(cur_ta.tile), TileY(new_ta.tile));
1214 new_ta.w = std::max(TileX(cur_ta.tile) + cur_ta.w, TileX(new_ta.tile) + new_ta.w) - x;
1215 new_ta.h = std::max(TileY(cur_ta.tile) + cur_ta.h, TileY(new_ta.tile) + new_ta.h) - y;
1216 new_ta.tile = TileXY(x, y);
1217
1218 /* make sure the final size is not too big. */
1219 if (new_ta.w > _settings_game.station.station_spread || new_ta.h > _settings_game.station.station_spread) {
1220 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
1221 }
1222
1223 return CommandCost();
1224}
1225
1227template <>
1229{
1230 /* Use predefined layout if it exists. Mask bit zero which will indicate axis. */
1231 if (!stl.layout.empty()) return this->stl.layout[this->position] & ~1;
1232
1233 if (this->stl.length == 1) {
1234 /* Special case for 1-long platforms, all bare platforms except one small building. */
1235 return this->position == ((this->stl.platforms - 1) / 2) ? 2 : 0;
1236 }
1237
1238 if ((this->position < this->stl.length && (this->stl.platforms % 2 == 1))) {
1239 /* Number of tracks is odd, make the first platform bare with a small building. */
1240 return this->position == ((this->stl.length - 1) / 2) ? 2 : 0;
1241 }
1242
1243 if (this->stl.length > 4 && ((this->position % this->stl.length) == 0 || (this->position % this->stl.length) == this->stl.length - 1)) {
1244 /* Station is longer than 4 tiles, place bare platforms at either end. */
1245 return 0;
1246 }
1247
1248 /* None of the above so must be north or south part of larger station. */
1249 return (((this->position / this->stl.length) % 2) == (this->stl.platforms % 2)) ? 4 : 6;
1250}
1251
1265template <class T, StringID error_message, class F>
1266CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
1267{
1268 assert(*st == nullptr);
1269 bool check_surrounding = true;
1270
1271 if (existing_station != StationID::Invalid()) {
1272 if (adjacent && existing_station != station_to_join) {
1273 /* You can't build an adjacent station over the top of one that
1274 * already exists. */
1275 return CommandCost(error_message);
1276 } else {
1277 /* Extend the current station, and don't check whether it will
1278 * be near any other stations. */
1279 T *candidate = T::GetIfValid(existing_station);
1280 if (candidate != nullptr && filter(candidate)) *st = candidate;
1281 check_surrounding = (*st == nullptr);
1282 }
1283 } else {
1284 /* There's no station here. Don't check the tiles surrounding this
1285 * one if the company wanted to build an adjacent station. */
1286 if (adjacent) check_surrounding = false;
1287 }
1288
1289 if (check_surrounding) {
1290 /* Make sure there is no more than one other station around us that is owned by us. */
1291 CommandCost ret = GetStationAround(ta, existing_station, _current_company, st, filter);
1292 if (ret.Failed()) return ret;
1293 }
1294
1295 /* Distant join */
1296 if (*st == nullptr && station_to_join != StationID::Invalid()) *st = T::GetIfValid(station_to_join);
1297
1298 return CommandCost();
1299}
1300
1310static CommandCost FindJoiningStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
1311{
1312 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_RAILWAY_STATION_FIRST>(existing_station, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
1313}
1314
1325CommandCost FindJoiningWaypoint(StationID existing_waypoint, StationID waypoint_to_join, bool adjacent, TileArea ta, Waypoint **wp, bool is_road)
1326{
1327 if (is_road) {
1328 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); });
1329 } else {
1330 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); });
1331 }
1332}
1333
1345
1357
1372static 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)
1373{
1375 bool length_price_ready = true;
1376 uint8_t tracknum = 0;
1377 int allowed_z = -1;
1378 for (TileIndex cur_tile : tile_area) {
1379 /* Clear the land below the station. */
1380 CommandCost ret = CheckFlatLandRailStation(cur_tile, tile_area.tile, allowed_z, flags, axis, station, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1381 if (ret.Failed()) return ret;
1382
1383 /* Only add _price[Price::BuildStationRailLength] once for each valid plat_len. */
1384 if (tracknum == numtracks) {
1385 length_price_ready = true;
1386 tracknum = 0;
1387 } else {
1388 tracknum++;
1389 }
1390
1391 /* AddCost for new or rotated rail stations. */
1392 if (!IsRailStationTile(cur_tile) || (IsRailStationTile(cur_tile) && GetRailStationAxis(cur_tile) != axis)) {
1393 cost.AddCost(ret.GetCost());
1395 cost.AddCost(RailBuildCost(rt));
1396
1397 if (length_price_ready) {
1399 length_price_ready = false;
1400 }
1401 }
1402 }
1403
1404 return cost;
1405}
1406
1413static StationSpec::TileFlags GetStationTileFlags(StationGfx gfx, const StationSpec *statspec)
1414{
1415 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1416 if (statspec == nullptr || gfx >= statspec->tileflags.size()) return gfx < 4 ? StationSpec::TileFlag::Pylons : StationSpec::TileFlags{};
1417 return statspec->tileflags[gfx];
1418}
1419
1426{
1427 const auto flags = GetStationTileFlags(GetStationGfx(tile), statspec);
1431}
1432
1447CommandCost 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)
1448{
1449 /* Does the authority allow this? */
1450 CommandCost ret = CheckIfAuthorityAllowsNewStation(tile_org, flags);
1451 if (ret.Failed()) return ret;
1452
1453 if (!ValParamRailType(rt) || !IsValidAxis(axis)) return CMD_ERROR;
1454
1455 /* Check if the given station class is valid */
1456 if (spec_class.base() >= StationClass::GetClassCount()) return CMD_ERROR;
1457 const StationClass *cls = StationClass::Get(spec_class);
1458 if (IsWaypointClass(*cls)) return CMD_ERROR;
1459 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
1460 if (plat_len == 0 || numtracks == 0) return CMD_ERROR;
1461
1462 int w_org, h_org;
1463 if (axis == Axis::X) {
1464 w_org = plat_len;
1465 h_org = numtracks;
1466 } else {
1467 h_org = plat_len;
1468 w_org = numtracks;
1469 }
1470
1471 /* Check if the first tile and the last tile are valid */
1472 if (!IsValidTile(tile_org) || TileAddWrap(tile_org, w_org - 1, h_org - 1) == INVALID_TILE) return CMD_ERROR;
1473
1474 bool reuse = (station_to_join != NEW_STATION);
1475 if (!reuse) station_to_join = StationID::Invalid();
1476 bool distant_join = (station_to_join != StationID::Invalid());
1477
1478 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
1479
1480 if (h_org > _settings_game.station.station_spread || w_org > _settings_game.station.station_spread) return CMD_ERROR;
1481
1482 /* these values are those that will be stored in train_tile and station_platforms */
1483 TileArea new_location(tile_org, w_org, h_org);
1484
1485 /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
1486 StationID est = StationID::Invalid();
1487 std::vector<Train *> affected_vehicles;
1488 /* Add construction and clearing expenses. */
1489 CommandCost cost = CalculateRailStationCost(new_location, flags, axis, &est, rt, affected_vehicles, spec_class, spec_index, plat_len, numtracks);
1490 if (cost.Failed()) return cost;
1491
1492 Station *st = nullptr;
1493 ret = FindJoiningStation(est, station_to_join, adjacent, new_location, &st);
1494 if (ret.Failed()) return ret;
1495
1496 ret = BuildStationPart(&st, flags, reuse, new_location, StationNaming::Rail);
1497 if (ret.Failed()) return ret;
1498
1499 if (st != nullptr && st->train_station.tile != INVALID_TILE) {
1500 ret = CanExpandRailStation(st, new_location);
1501 if (ret.Failed()) return ret;
1502 }
1503
1504 const StationSpec *statspec = StationClass::Get(spec_class)->GetSpec(spec_index);
1505 TileIndexDiff tile_delta = TileOffsByAxis(axis); // offset to go to the next platform tile
1506 TileIndexDiff track_delta = TileOffsByAxis(OtherAxis(axis)); // offset to go to the next track
1507
1508 RailStationTileLayout<StationType::Rail> stl{statspec, numtracks, plat_len};
1509 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1510 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1511 /* Don't check the layout if there's no bridge above anyway. */
1512 if (!IsBridgeAbove(tile)) continue;
1513
1514 StationGfx gfx = *it + to_underlying(axis);
1515 if (statspec != nullptr) {
1516 uint32_t platinfo = GetPlatformInfo(gfx, numtracks, plat_len, i, j, false);
1517 /* As the station is not yet completely finished, the station does not yet exist. */
1518 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, INVALID_TILE);
1519 if (callback != CALLBACK_FAILED && callback <= UINT8_MAX) gfx = (callback & ~1) + to_underlying(axis);
1520 }
1521
1522 ret = IsRailStationBridgeAboveOk(tile, statspec, StationType::Rail, gfx);
1523 if (ret.Failed()) return ret;
1524 }
1525 }
1526
1527 /* Check if we can allocate a custom stationspec to this station */
1528 auto specindex = AllocateSpecToStation(statspec, st);
1529 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
1530
1531 if (statspec != nullptr) {
1532 /* Perform NewStation checks */
1533
1534 /* Check if the station size is permitted */
1535 if (HasBit(statspec->disallowed_platforms, std::min(numtracks - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_NUMBER_TRACKS);
1536 if (HasBit(statspec->disallowed_lengths, std::min(plat_len - 1, 7))) return CommandCost(STR_ERROR_STATION_DISALLOWED_LENGTH);
1537
1538 /* Check if the station is buildable */
1540 uint16_t cb_res = GetStationCallback(CBID_STATION_AVAILABILITY, 0, 0, statspec, nullptr, INVALID_TILE);
1542 }
1543 }
1544
1545 if (flags.Test(DoCommandFlag::Execute)) {
1546 st->train_station = new_location;
1547 st->AddFacility(StationFacility::Train, new_location.tile);
1548
1549 st->rect.BeforeAddRect(tile_org, w_org, h_org, StationRect::ADD_TRY);
1550
1551 if (specindex.has_value()) AssignSpecToStation(statspec, st, *specindex);
1552 if (statspec != nullptr) {
1553 /* Include this station spec's animation trigger bitmask
1554 * in the station's cached copy. */
1555 st->cached_anim_triggers.Set(statspec->animation.triggers);
1556 }
1557
1558 Track track = AxisToTrack(axis);
1559 Company *c = Company::Get(st->owner);
1560 for (auto [i, it, tile_track] = std::make_tuple(0, stl.begin(), tile_org); i != numtracks; ++i, tile_track += track_delta) {
1561 for (auto [j, tile] = std::make_tuple(0, tile_track); j != plat_len; ++j, tile += tile_delta, ++it) {
1562 if (IsRailStationTile(tile) && HasStationReservation(tile)) {
1563 /* Check for trains having a reservation for this tile. */
1565 if (v != nullptr) {
1566 affected_vehicles.push_back(v);
1568 }
1569 }
1570
1571 /* Railtype can change when overbuilding. */
1572 if (IsRailStationTile(tile)) {
1573 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[GetRailType(tile)]--;
1575 }
1576
1577 /* Remove animation if overbuilding */
1578 DeleteAnimatedTile(tile);
1579 uint8_t old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
1580
1581 MakeRailStation(tile, st->owner, st->index, axis, *it, rt);
1582 /* Free the spec if we overbuild something */
1583 DeallocateSpecFromStation(st, old_specindex);
1584 if (statspec == nullptr) DeleteNewGRFInspectWindow(GrfSpecFeature::Stations, tile);
1585
1586 SetCustomStationSpecIndex(tile, *specindex);
1587 SetStationTileRandomBits(tile, GB(Random(), 0, 4));
1588 SetAnimationFrame(tile, 0);
1589
1590 if (statspec != nullptr) {
1591 uint32_t platinfo = GetPlatformInfo(*it + to_underlying(axis), numtracks, plat_len, i, j, false);
1592
1593 /* As the station is not yet completely finished, the station does not yet exist. */
1594 uint16_t callback = GetStationCallback(CBID_STATION_BUILD_TILE_LAYOUT, platinfo, 0, statspec, nullptr, tile);
1595 if (callback != CALLBACK_FAILED) {
1596 if (callback <= UINT8_MAX) {
1597 SetStationGfx(tile, (callback & ~1) + to_underlying(axis));
1598 } else {
1600 }
1601 }
1602
1603 /* Trigger station animation -- after building? */
1604 TriggerStationAnimation(st, tile, StationAnimationTrigger::Built);
1605 }
1606
1607 SetRailStationTileFlags(tile, statspec);
1608
1609 if (!IsStationTileBlocked(tile)) c->infrastructure.rail[rt]++;
1611 }
1612 AddTrackToSignalBuffer(tile_track, track, _current_company);
1613 YapfNotifyTrackLayoutChange(tile_track, track);
1614 }
1615
1616 for (uint i = 0; i < affected_vehicles.size(); ++i) {
1617 /* Restore reservations of trains. */
1618 RestoreTrainReservation(affected_vehicles[i]);
1619 }
1620
1621 /* Check whether we need to expand the reservation of trains already on the station. */
1622 TileArea update_reservation_area;
1623 if (axis == Axis::X) {
1624 update_reservation_area = TileArea(tile_org, 1, numtracks);
1625 } else {
1626 update_reservation_area = TileArea(tile_org, numtracks, 1);
1627 }
1628
1629 for (TileIndex tile : update_reservation_area) {
1630 /* Don't even try to make eye candy parts reserved. */
1631 if (IsStationTileBlocked(tile)) continue;
1632
1633 DiagDirection dir = AxisToDiagDir(axis);
1634 TileIndexDiff tile_offset = TileOffsByDiagDir(dir);
1635 TileIndex platform_begin = tile;
1636 TileIndex platform_end = tile;
1637
1638 /* We can only account for tiles that are reachable from this tile, so ignore primarily blocked tiles while finding the platform begin and end. */
1639 for (TileIndex next_tile = platform_begin - tile_offset; IsCompatibleTrainStationTile(next_tile, platform_begin); next_tile -= tile_offset) {
1640 platform_begin = next_tile;
1641 }
1642 for (TileIndex next_tile = platform_end + tile_offset; IsCompatibleTrainStationTile(next_tile, platform_end); next_tile += tile_offset) {
1643 platform_end = next_tile;
1644 }
1645
1646 /* If there is at least on reservation on the platform, we reserve the whole platform. */
1647 bool reservation = false;
1648 for (TileIndex t = platform_begin; !reservation && t <= platform_end; t += tile_offset) {
1649 reservation = HasStationReservation(t);
1650 }
1651
1652 if (reservation) {
1653 SetRailStationPlatformReservation(platform_begin, dir, true);
1654 }
1655 }
1656
1657 st->MarkTilesDirty(false);
1659 }
1660
1661 return cost;
1662}
1663
1664static TileArea MakeStationAreaSmaller(BaseStation *st, TileArea ta, bool (*func)(BaseStation *, TileIndex))
1665{
1666restart:
1667
1668 /* too small? */
1669 if (ta.w != 0 && ta.h != 0) {
1670 /* check the left side, x = constant, y changes */
1671 for (uint i = 0; !func(st, ta.tile + TileDiffXY(0, i));) {
1672 /* the left side is unused? */
1673 if (++i == ta.h) {
1674 ta.tile += TileDiffXY(1, 0);
1675 ta.w--;
1676 goto restart;
1677 }
1678 }
1679
1680 /* check the right side, x = constant, y changes */
1681 for (uint i = 0; !func(st, ta.tile + TileDiffXY(ta.w - 1, i));) {
1682 /* the right side is unused? */
1683 if (++i == ta.h) {
1684 ta.w--;
1685 goto restart;
1686 }
1687 }
1688
1689 /* check the upper side, y = constant, x changes */
1690 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, 0));) {
1691 /* the left side is unused? */
1692 if (++i == ta.w) {
1693 ta.tile += TileDiffXY(0, 1);
1694 ta.h--;
1695 goto restart;
1696 }
1697 }
1698
1699 /* check the lower side, y = constant, x changes */
1700 for (uint i = 0; !func(st, ta.tile + TileDiffXY(i, ta.h - 1));) {
1701 /* the left side is unused? */
1702 if (++i == ta.w) {
1703 ta.h--;
1704 goto restart;
1705 }
1706 }
1707 } else {
1708 ta.Clear();
1709 }
1710
1711 return ta;
1712}
1713
1714static bool TileBelongsToRailStation(BaseStation *st, TileIndex tile)
1715{
1716 return st->TileBelongsToRailStation(tile);
1717}
1718
1719static void MakeRailStationAreaSmaller(BaseStation *st)
1720{
1721 st->train_station = MakeStationAreaSmaller(st, st->train_station, TileBelongsToRailStation);
1722}
1723
1724static bool TileBelongsToShipStation(BaseStation *st, TileIndex tile)
1725{
1726 return IsDockTile(tile) && GetStationIndex(tile) == st->index;
1727}
1728
1729static void MakeShipStationAreaSmaller(Station *st)
1730{
1731 st->ship_station = MakeStationAreaSmaller(st, st->ship_station, TileBelongsToShipStation);
1732 UpdateStationDockingTiles(st);
1733}
1734
1735static bool TileBelongsToRoadWaypointStation(BaseStation *st, TileIndex tile)
1736{
1737 return IsRoadWaypointTile(tile) && GetStationIndex(tile) == st->index;
1738}
1739
1740void MakeRoadWaypointStationAreaSmaller(BaseStation *st, TileArea &road_waypoint_area)
1741{
1742 road_waypoint_area = MakeStationAreaSmaller(st, road_waypoint_area, TileBelongsToRoadWaypointStation);
1743}
1744
1755template <class T>
1756CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector<T *> &affected_stations, DoCommandFlags flags, Money removal_cost, bool keep_rail)
1757{
1758 /* Count of the number of tiles removed */
1759 int quantity = 0;
1761 /* Accumulator for the errors seen during clearing. If no errors happen,
1762 * and the quantity is 0 there is no station. Otherwise it will be one
1763 * of the other error that got accumulated. */
1764 CommandCost error;
1765
1766 /* Do the action for every tile into the area */
1767 for (TileIndex tile : ta) {
1768 /* Make sure the specified tile is a rail station */
1769 if (!HasStationTileRail(tile)) continue;
1770
1771 /* If there is a vehicle on ground, do not allow to remove (flood) the tile */
1773 error.AddCost(std::move(ret));
1774 if (error.Failed()) continue;
1775
1776 /* Check ownership of station */
1777 T *st = T::GetByTile(tile);
1778 if (st == nullptr) continue;
1779
1781 ret = CheckOwnership(st->owner);
1782 error.AddCost(std::move(ret));
1783 if (error.Failed()) continue;
1784 }
1785
1786 /* If we reached here, the tile is valid so increase the quantity of tiles we will remove */
1787 quantity++;
1788
1789 if (keep_rail || IsStationTileBlocked(tile)) {
1790 /* Don't refund the 'steel' of the track when we keep the
1791 * rail, or when the tile didn't have any rail at all. */
1792 total_cost.AddCost(-_price[Price::ClearRail]);
1793 }
1794
1795 if (flags.Test(DoCommandFlag::Execute)) {
1796 /* read variables before the station tile is removed */
1797 uint specindex = GetCustomStationSpecIndex(tile);
1798 Track track = GetRailStationTrack(tile);
1799 Owner owner = GetTileOwner(tile);
1800 RailType rt = GetRailType(tile);
1801 Train *v = nullptr;
1802
1803 if (HasStationReservation(tile)) {
1804 v = GetTrainForReservation(tile, track);
1805 if (v != nullptr) FreeTrainReservation(v);
1806 }
1807
1808 bool build_rail = keep_rail && !IsStationTileBlocked(tile);
1809 if (!build_rail && !IsStationTileBlocked(tile)) Company::Get(owner)->infrastructure.rail[rt]--;
1810
1811 DoClearSquare(tile);
1813 if (build_rail) MakeRailNormal(tile, owner, TrackToTrackBits(track), rt);
1814 Company::Get(owner)->infrastructure.station--;
1816
1817 st->tile_waiting_random_triggers.erase(tile);
1818 st->rect.AfterRemoveTile(st, tile);
1819 AddTrackToSignalBuffer(tile, track, owner);
1820 YapfNotifyTrackLayoutChange(tile, track);
1821
1822 DeallocateSpecFromStation(st, specindex);
1823
1824 include(affected_stations, st);
1825
1826 if (v != nullptr) RestoreTrainReservation(v);
1827 }
1828 }
1829
1830 if (quantity == 0) return error.Failed() ? error : CommandCost(STR_ERROR_THERE_IS_NO_STATION);
1831
1832 for (T *st : affected_stations) {
1833
1834 /* now we need to make the "spanned" area of the railway station smaller
1835 * if we deleted something at the edges.
1836 * we also need to adjust train_tile. */
1837 MakeRailStationAreaSmaller(st);
1838 UpdateStationSignCoord(st);
1839
1840 /* if we deleted the whole station, delete the train facility. */
1841 if (st->train_station.tile == INVALID_TILE) {
1843 SetWindowClassesDirty(WindowClass::VehicleOrders);
1844 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1845 MarkCatchmentTilesDirty();
1846 st->UpdateVirtCoord();
1848 }
1849 }
1850
1851 total_cost.AddCost(quantity * removal_cost);
1852 return total_cost;
1853}
1854
1864CommandCost CmdRemoveFromRailStation(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
1865{
1866 if (end == 0) end = start;
1867 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1868
1869 TileArea ta(start, end);
1870 std::vector<Station *> affected_stations;
1871
1872 CommandCost ret = RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearStationRail], keep_rail);
1873 if (ret.Failed()) return ret;
1874
1875 /* Do all station specific functions here. */
1876 for (Station *st : affected_stations) {
1877
1878 if (st->train_station.tile == INVALID_TILE) SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_TRAINS);
1879 st->MarkTilesDirty(false);
1880 MarkCatchmentTilesDirty();
1881 st->RecomputeCatchment();
1882 }
1883
1884 /* Now apply the rail cost to the number that we deleted */
1885 return ret;
1886}
1887
1897CommandCost CmdRemoveFromRailWaypoint(DoCommandFlags flags, TileIndex start, TileIndex end, bool keep_rail)
1898{
1899 if (end == 0) end = start;
1900 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
1901
1902 TileArea ta(start, end);
1903 std::vector<Waypoint *> affected_stations;
1904
1905 return RemoveFromRailBaseStation(ta, affected_stations, flags, _price[Price::ClearWaypointRail], keep_rail);
1906}
1907
1908
1917template <class T>
1918CommandCost RemoveRailStation(T *st, DoCommandFlags flags, Money removal_cost)
1919{
1920 /* Current company owns the station? */
1922 CommandCost ret = CheckOwnership(st->owner);
1923 if (ret.Failed()) return ret;
1924 }
1925
1926 /* determine width and height of platforms */
1927 TileArea ta = st->train_station;
1928
1929 assert(ta.w != 0 && ta.h != 0);
1930
1932 /* clear all areas of the station */
1933 for (TileIndex tile : ta) {
1934 /* only remove tiles that are actually train station tiles */
1935 if (st->TileBelongsToRailStation(tile)) {
1936 std::vector<T*> affected_stations; // dummy
1937 CommandCost ret = RemoveFromRailBaseStation(TileArea(tile, 1, 1), affected_stations, flags, removal_cost, false);
1938 if (ret.Failed()) return ret;
1939 cost.AddCost(ret.GetCost());
1940 }
1941 }
1942
1943 return cost;
1944}
1945
1952static CommandCost RemoveRailStation(TileIndex tile, DoCommandFlags flags)
1953{
1954 /* if there is flooding, remove platforms tile by tile */
1956 return Command<Commands::RemoveFromRailStation>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1957 }
1958
1959 Station *st = Station::GetByTile(tile);
1961
1963
1964 return cost;
1965}
1966
1973static CommandCost RemoveRailWaypoint(TileIndex tile, DoCommandFlags flags)
1974{
1975 /* if there is flooding, remove waypoints tile by tile */
1977 return Command<Commands::RemoveFromRailWaypoint>::Do(DoCommandFlag::Execute, tile, TileIndex{}, false);
1978 }
1979
1981}
1982
1983
1989static RoadStop **FindRoadStopSpot(bool truck_station, Station *st)
1990{
1991 RoadStop **primary_stop = (truck_station) ? &st->truck_stops : &st->bus_stops;
1992
1993 if (*primary_stop == nullptr) {
1994 /* we have no roadstop of the type yet, so write a "primary stop" */
1995 return primary_stop;
1996 } else {
1997 /* there are stops already, so append to the end of the list */
1998 RoadStop *stop = *primary_stop;
1999 while (stop->next != nullptr) stop = stop->next;
2000 return &stop->next;
2001 }
2002}
2003
2004static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
2005CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index = -1);
2006
2016static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID station_to_join, bool adjacent, TileArea ta, Station **st)
2017{
2018 return FindJoiningBaseStation<Station, STR_ERROR_MUST_REMOVE_ROAD_STOP_FIRST>(existing_stop, station_to_join, adjacent, ta, st, [](const Station *) -> bool { return true; });
2019}
2020
2035CommandCost 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)
2036{
2037 DiagDirections invalid_dirs = is_drive_through ? AxisToDiagDirs(axis) : ddir;
2038
2039 /* Check every tile in the area. */
2040 int allowed_z = -1;
2042 for (TileIndex cur_tile : tile_area) {
2043 CommandCost ret = CheckFlatLandRoadStop(cur_tile, allowed_z, roadstopspec, flags, invalid_dirs, is_drive_through, station_type, axis, station, rt);
2044 if (ret.Failed()) return ret;
2045
2046 bool is_preexisting_roadstop = IsTileType(cur_tile, TileType::Station) && IsAnyRoadStop(cur_tile);
2047
2048 /* Only add costs if a stop doesn't already exist in the location */
2049 if (!is_preexisting_roadstop) {
2050 cost.AddCost(ret.GetCost());
2051 cost.AddCost(unit_cost);
2052 }
2053 }
2054
2055 return cost;
2056}
2057
2074CommandCost CmdBuildRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t length, RoadStopType stop_type, bool is_drive_through,
2075 DiagDirection ddir, RoadType rt, RoadStopClassID spec_class, uint16_t spec_index, StationID station_to_join, bool adjacent)
2076{
2077 if (!ValParamRoadType(rt) || !IsValidDiagDirection(ddir) || stop_type >= RoadStopType::End) return CMD_ERROR;
2078 bool reuse = (station_to_join != NEW_STATION);
2079 if (!reuse) station_to_join = StationID::Invalid();
2080 bool distant_join = (station_to_join != StationID::Invalid());
2081
2082 /* Check if the given station class is valid */
2083 if (spec_class.base() >= RoadStopClass::GetClassCount()) return CMD_ERROR;
2084 const RoadStopClass *cls = RoadStopClass::Get(spec_class);
2085 if (IsWaypointClass(*cls)) return CMD_ERROR;
2086 if (spec_index >= cls->GetSpecCount()) return CMD_ERROR;
2087
2088 const RoadStopSpec *roadstopspec = cls->GetSpec(spec_index);
2089 if (roadstopspec != nullptr) {
2090 if (stop_type == RoadStopType::Truck && roadstopspec->stop_type != ROADSTOPTYPE_FREIGHT && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2091 if (stop_type == RoadStopType::Bus && roadstopspec->stop_type != ROADSTOPTYPE_PASSENGER && roadstopspec->stop_type != ROADSTOPTYPE_ALL) return CMD_ERROR;
2092 if (!is_drive_through && roadstopspec->flags.Test(RoadStopSpecFlag::DriveThroughOnly)) return CMD_ERROR;
2093 }
2094
2095 /* Check if the requested road stop is too big */
2096 if (width > _settings_game.station.station_spread || length > _settings_game.station.station_spread) return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2097 /* Check for incorrect width / length. */
2098 if (width == 0 || length == 0) return CMD_ERROR;
2099 /* Check if the first tile and the last tile are valid */
2100 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, length - 1) == INVALID_TILE) return CMD_ERROR;
2101
2102 TileArea roadstop_area(tile, width, length);
2103
2104 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2105
2106 /* Trams only have drive through stops */
2107 if (!is_drive_through && RoadTypeIsTram(rt)) return CMD_ERROR;
2108
2109 Axis axis = DiagDirToAxis(ddir);
2110
2112 if (ret.Failed()) return ret;
2113
2114 bool is_truck_stop = stop_type != RoadStopType::Bus;
2115
2116 /* Total road stop cost. */
2117 Money unit_cost;
2118 if (roadstopspec != nullptr) {
2119 unit_cost = roadstopspec->GetBuildCost(is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus);
2120 } else {
2121 unit_cost = _price[is_truck_stop ? Price::BuildStationTruck : Price::BuildStationBus];
2122 }
2123 StationID est = StationID::Invalid();
2124 CommandCost cost = CalculateRoadStopCost(roadstop_area, flags, is_drive_through, is_truck_stop ? StationType::Truck : StationType::Bus, roadstopspec, axis, ddir, &est, rt, unit_cost);
2125 if (cost.Failed()) return cost;
2126
2127 Station *st = nullptr;
2128 ret = FindJoiningRoadStop(est, station_to_join, adjacent, roadstop_area, &st);
2129 if (ret.Failed()) return ret;
2130
2131 /* Check if this number of road stops can be allocated. */
2132 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);
2133
2134 ret = BuildStationPart(&st, flags, reuse, roadstop_area, StationNaming::Road);
2135 if (ret.Failed()) return ret;
2136
2137 /* Check if we can allocate a custom stationspec to this station */
2138 auto specindex = AllocateSpecToRoadStop(roadstopspec, st);
2139 if (!specindex.has_value()) return CommandCost(STR_ERROR_TOO_MANY_STATION_SPECS);
2140
2141 if (roadstopspec != nullptr) {
2142 /* Perform NewGRF checks */
2143
2144 /* Check if the road stop is buildable */
2145 if (roadstopspec->callback_mask.Test(RoadStopCallbackMask::Avail)) {
2146 uint16_t cb_res = GetRoadStopCallback(CBID_STATION_AVAILABILITY, 0, 0, roadstopspec, nullptr, INVALID_TILE, rt, is_truck_stop ? StationType::Truck : StationType::Bus, 0);
2147 if (cb_res != CALLBACK_FAILED && !Convert8bitBooleanCallback(roadstopspec->grf_prop.grffile, CBID_STATION_AVAILABILITY, cb_res)) return CMD_ERROR;
2148 }
2149 }
2150
2151 if (flags.Test(DoCommandFlag::Execute)) {
2152 if (specindex.has_value()) AssignSpecToRoadStop(roadstopspec, st, *specindex);
2153 /* Check every tile in the area. */
2154 for (TileIndex cur_tile : roadstop_area) {
2155 /* Get existing road types and owners before any tile clearing */
2156 RoadType road_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Road) : INVALID_ROADTYPE;
2157 RoadType tram_rt = MayHaveRoad(cur_tile) ? GetRoadType(cur_tile, RoadTramType::Tram) : INVALID_ROADTYPE;
2158 Owner road_owner = road_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Road) : _current_company;
2159 Owner tram_owner = tram_rt != INVALID_ROADTYPE ? GetRoadOwner(cur_tile, RoadTramType::Tram) : _current_company;
2160
2161 if (IsTileType(cur_tile, TileType::Station) && IsStationRoadStop(cur_tile)) {
2162 RemoveRoadStop(cur_tile, flags, *specindex);
2163 }
2164
2165 if (roadstopspec != nullptr) {
2166 /* Include this road stop spec's animation trigger bitmask
2167 * in the station's cached copy. */
2168 st->cached_roadstop_anim_triggers.Set(roadstopspec->animation.triggers);
2169 }
2170
2171 RoadStop *road_stop = RoadStop::Create(cur_tile);
2172 /* Insert into linked list of RoadStops. */
2173 RoadStop **currstop = FindRoadStopSpot(is_truck_stop, st);
2174 *currstop = road_stop;
2175
2176 if (is_truck_stop) {
2177 st->truck_station.Add(cur_tile);
2178 } else {
2179 st->bus_station.Add(cur_tile);
2180 }
2181
2182 /* Initialize an empty station. */
2183 st->AddFacility(is_truck_stop ? StationFacility::TruckStop : StationFacility::BusStop, cur_tile);
2184
2185 st->rect.BeforeAddTile(cur_tile, StationRect::ADD_TRY);
2186
2187 RoadStopType rs_type = is_truck_stop ? RoadStopType::Truck : RoadStopType::Bus;
2188 if (is_drive_through) {
2189 /* Update company infrastructure counts. If the current tile is a normal road tile, remove the old
2190 * bits first. */
2191 if (IsNormalRoadTile(cur_tile)) {
2192 UpdateCompanyRoadInfrastructure(road_rt, road_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Road).Count()));
2193 UpdateCompanyRoadInfrastructure(tram_rt, tram_owner, -static_cast<int>(GetRoadBits(cur_tile, RoadTramType::Tram).Count()));
2194 }
2195
2196 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2197 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2198
2199 MakeDriveThroughRoadStop(cur_tile, st->owner, road_owner, tram_owner, st->index, (rs_type == RoadStopType::Bus ? StationType::Bus : StationType::Truck), road_rt, tram_rt, axis);
2200 road_stop->MakeDriveThrough();
2201 } else {
2202 if (road_rt == INVALID_ROADTYPE && RoadTypeIsRoad(rt)) road_rt = rt;
2203 if (tram_rt == INVALID_ROADTYPE && RoadTypeIsTram(rt)) tram_rt = rt;
2204 MakeRoadStop(cur_tile, st->owner, st->index, rs_type, road_rt, tram_rt, ddir);
2205 }
2208 Company::Get(st->owner)->infrastructure.station++;
2209
2210 SetCustomRoadStopSpecIndex(cur_tile, *specindex);
2211 if (roadstopspec != nullptr) {
2212 st->SetRoadStopRandomBits(cur_tile, GB(Random(), 0, 8));
2213 TriggerRoadStopAnimation(st, cur_tile, StationAnimationTrigger::Built);
2214 }
2215
2216 MarkTileDirtyByTile(cur_tile);
2217 }
2218
2219 if (st != nullptr) {
2221 }
2222 }
2223 return cost;
2224}
2225
2233static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2234{
2235 Station *st = Station::GetByTile(tile);
2236
2238 CommandCost ret = CheckOwnership(st->owner);
2239 if (ret.Failed()) return ret;
2240 }
2241
2242 bool is_truck = IsTruckStop(tile);
2243
2244 RoadStop **primary_stop;
2245 RoadStop *cur_stop;
2246 if (is_truck) { // truck stop
2247 primary_stop = &st->truck_stops;
2248 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Truck);
2249 } else {
2250 primary_stop = &st->bus_stops;
2251 cur_stop = RoadStop::GetByTile(tile, RoadStopType::Bus);
2252 }
2253
2254 assert(cur_stop != nullptr);
2255
2256 /* don't do the check for drive-through road stops when company bankrupts */
2258 /* remove the 'going through road stop' status from all vehicles on that tile */
2259 if (flags.Test(DoCommandFlag::Execute)) {
2260 for (Vehicle *v : VehiclesOnTile(tile)) {
2261 if (v->type != VehicleType::Road) continue;
2262 /* Okay... we are a road vehicle on a drive through road stop.
2263 * But that road stop has just been removed, so we need to make
2264 * sure we are in a valid state... however, vehicles can also
2265 * turn on road stop tiles, so only clear the 'road stop' state
2266 * bits and only when the state was 'in road stop', otherwise
2267 * we'll end up clearing the turn around bits. */
2270 }
2271 }
2272 } else {
2274 if (ret.Failed()) return ret;
2275 }
2276
2277 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2278
2279 if (flags.Test(DoCommandFlag::Execute)) {
2280 if (*primary_stop == cur_stop) {
2281 /* removed the first stop in the list */
2282 *primary_stop = cur_stop->next;
2283 /* removed the only stop? */
2284 if (*primary_stop == nullptr) {
2286 SetWindowClassesDirty(WindowClass::VehicleOrders);
2287 }
2288 } else {
2289 /* tell the predecessor in the list to skip this stop */
2290 RoadStop *pred = *primary_stop;
2291 while (pred->next != cur_stop) pred = pred->next;
2292 pred->next = cur_stop->next;
2293 }
2294
2295 /* Update company infrastructure counts. */
2296 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2297 RoadType rt = GetRoadType(tile, rtt);
2299 }
2300
2301 Company::Get(st->owner)->infrastructure.station--;
2303
2304 uint specindex = GetCustomRoadStopSpecIndex(tile);
2305
2307
2308 if (IsDriveThroughStopTile(tile)) {
2309 /* Clears the tile for us */
2310 cur_stop->ClearDriveThrough();
2311 DeleteAnimatedTile(tile);
2312 } else {
2313 DoClearSquare(tile);
2314 }
2315
2316 delete cur_stop;
2317
2318 /* Make sure no vehicle is going to the old roadstop. Narrow the search to any road vehicles with an order to
2319 * this station, then look for any currently heading to the tile. */
2320 StationID station_id = st->index;
2322 [](const Vehicle *v) { return v->type == VehicleType::Road; },
2323 [station_id](const Order *order) { return order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id; },
2324 [station_id, tile](Vehicle *v) {
2325 if (v->current_order.IsType(OT_GOTO_STATION) && v->dest_tile == tile) {
2326 v->SetDestTile(v->GetOrderStationLocation(station_id));
2327 }
2328 }
2329 );
2330
2331 st->rect.AfterRemoveTile(st, tile);
2332
2333 if (replacement_spec_index < 0) st->AfterStationTileSetChange(false, is_truck ? StationType::Truck: StationType::Bus);
2334
2335 st->tile_waiting_random_triggers.erase(tile);
2336 st->RemoveRoadStopTileData(tile);
2337 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(st, specindex);
2338
2339 /* Update the tile area of the truck/bus stop */
2340 if (is_truck) {
2341 st->truck_station.Clear();
2342 for (const RoadStop *rs = st->truck_stops; rs != nullptr; rs = rs->next) st->truck_station.Add(rs->xy);
2343 } else {
2344 st->bus_station.Clear();
2345 for (const RoadStop *rs = st->bus_stops; rs != nullptr; rs = rs->next) st->bus_station.Add(rs->xy);
2346 }
2347 }
2348
2350 return CommandCost(ExpensesType::Construction, spec != nullptr ? spec->GetClearCost(category) : _price[category]);
2351}
2352
2360CommandCost RemoveRoadWaypointStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index)
2361{
2362 Waypoint *wp = Waypoint::GetByTile(tile);
2363
2365 CommandCost ret = CheckOwnership(wp->owner);
2366 if (ret.Failed()) return ret;
2367 }
2368
2369 /* Ignore vehicles when the company goes bankrupt. The road will remain, any vehicles going to the waypoint will be removed. */
2370 if (!flags.Test(DoCommandFlag::Bankrupt)) {
2372 if (ret.Failed()) return ret;
2373 }
2374
2375 const RoadStopSpec *spec = GetRoadStopSpec(tile);
2376
2377 if (flags.Test(DoCommandFlag::Execute)) {
2378 /* Update company infrastructure counts. */
2379 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2380 RoadType rt = GetRoadType(tile, rtt);
2382 }
2383
2384 Company::Get(wp->owner)->infrastructure.station--;
2386
2387 uint specindex = GetCustomRoadStopSpecIndex(tile);
2388
2390
2391 DoClearSquare(tile);
2392
2393 wp->rect.AfterRemoveTile(wp, tile);
2394
2395 wp->tile_waiting_random_triggers.erase(tile);
2396 wp->RemoveRoadStopTileData(tile);
2397 if ((int)specindex != replacement_spec_index) DeallocateSpecFromRoadStop(wp, specindex);
2398
2399 if (replacement_spec_index < 0) {
2400 MakeRoadWaypointStationAreaSmaller(wp, wp->road_waypoint_area);
2401
2402 UpdateStationSignCoord(wp);
2403
2404 /* if we deleted the whole waypoint, delete the road facility. */
2407 SetWindowWidgetDirty(WindowClass::StationView, wp->index, WID_SV_ROADVEHS);
2408 wp->UpdateVirtCoord();
2410 }
2411 }
2412 }
2413
2415}
2416
2425static CommandCost RemoveGenericRoadStop(DoCommandFlags flags, const TileArea &roadstop_area, bool road_waypoint, bool remove_road)
2426{
2428 CommandCost last_error(STR_ERROR_THERE_IS_NO_STATION);
2429 bool had_success = false;
2430
2431 for (TileIndex cur_tile : roadstop_area) {
2432 /* Make sure the specified tile is a road stop of the correct type */
2433 if (!IsTileType(cur_tile, TileType::Station) || !IsAnyRoadStop(cur_tile) || IsRoadWaypoint(cur_tile) != road_waypoint) continue;
2434
2435 /* Save information on to-be-restored roads before the stop is removed. */
2436 RoadBits road_bits{};
2439 if (IsDriveThroughStopTile(cur_tile)) {
2440 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
2441 road_type[rtt] = GetRoadType(cur_tile, rtt);
2442 if (road_type[rtt] == INVALID_ROADTYPE) continue;
2443 road_owner[rtt] = GetRoadOwner(cur_tile, rtt);
2444 /* If we don't want to preserve our roads then restore only roads of others. */
2445 if (remove_road && road_owner[rtt] == _current_company) road_type[rtt] = INVALID_ROADTYPE;
2446 }
2447 road_bits = AxisToRoadBits(GetDriveThroughStopAxis(cur_tile));
2448 }
2449
2450 CommandCost ret;
2451 if (road_waypoint) {
2452 ret = RemoveRoadWaypointStop(cur_tile, flags);
2453 } else {
2454 ret = RemoveRoadStop(cur_tile, flags);
2455 }
2456 if (ret.Failed()) {
2457 last_error = std::move(ret);
2458 continue;
2459 }
2460 cost.AddCost(ret.GetCost());
2461 had_success = true;
2462
2463 /* Restore roads. */
2465 MakeRoadNormal(cur_tile, road_bits, road_type[RoadTramType::Road], road_type[RoadTramType::Tram], ClosestTownFromTile(cur_tile, UINT_MAX)->index,
2466 road_owner[RoadTramType::Road], road_owner[RoadTramType::Tram]);
2467
2468 /* Update company infrastructure counts. */
2469 int count = road_bits.Count();
2472 }
2473 }
2474
2475 return had_success ? cost : last_error;
2476}
2477
2488CommandCost CmdRemoveRoadStop(DoCommandFlags flags, TileIndex tile, uint8_t width, uint8_t height, RoadStopType stop_type, bool remove_road)
2489{
2490 if (stop_type >= RoadStopType::End) return CMD_ERROR;
2491 /* Check for incorrect width / height. */
2492 if (width == 0 || height == 0) return CMD_ERROR;
2493 /* Check if the first tile and the last tile are valid */
2494 if (!IsValidTile(tile) || TileAddWrap(tile, width - 1, height - 1) == INVALID_TILE) return CMD_ERROR;
2495 /* Bankrupting company is not supposed to remove roads, there may be road vehicles. */
2496 if (remove_road && flags.Test(DoCommandFlag::Bankrupt)) return CMD_ERROR;
2497
2498 TileArea roadstop_area(tile, width, height);
2499
2500 return RemoveGenericRoadStop(flags, roadstop_area, false, remove_road);
2501}
2502
2511{
2512 if (end == 0) end = start;
2513 if (start >= Map::Size() || end >= Map::Size()) return CMD_ERROR;
2514
2515 TileArea roadstop_area(start, end);
2516
2517 return RemoveGenericRoadStop(flags, roadstop_area, true, false);
2518}
2519
2528uint8_t GetAirportNoiseLevelForDistance(const AirportSpec *as, uint distance)
2529{
2530 /* 0 cannot be accounted, and 1 is the lowest that can be reduced from town.
2531 * So no need to go any further*/
2532 if (as->noise_level < 2) return as->noise_level;
2533
2534 /* The steps for measuring noise reduction are based on the "magical" (and arbitrary) 8 base distance
2535 * adding the town_council_tolerance 4 times, as a way to graduate, depending of the tolerance.
2536 * Basically, it says that the less tolerant a town is, the bigger the distance before
2537 * an actual decrease can be granted */
2538 uint8_t town_tolerance_distance = 8 + (_settings_game.difficulty.town_council_tolerance * 4);
2539
2540 /* now, we want to have the distance segmented using the distance judged bareable by town
2541 * This will give us the coefficient of reduction the distance provides. */
2542 uint noise_reduction = distance / town_tolerance_distance;
2543
2544 /* If the noise reduction equals the airport noise itself, don't give it for free.
2545 * Otherwise, simply reduce the airport's level. */
2546 return noise_reduction >= as->noise_level ? 1 : as->noise_level - noise_reduction;
2547}
2548
2559Town *AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
2560{
2561 assert(Town::GetNumItems() > 0);
2562
2563 Town *nearest = nullptr;
2564
2565 auto width = as->size_x;
2566 auto height = as->size_y;
2567 if (rotation == Direction::E || rotation == Direction::W) std::swap(width, height);
2568
2569 uint perimeter_min_x = TileX(tile);
2570 uint perimeter_min_y = TileY(tile);
2571 uint perimeter_max_x = perimeter_min_x + width - 1;
2572 uint perimeter_max_y = perimeter_min_y + height - 1;
2573
2574 mindist = UINT_MAX - 1; // prevent overflow
2575
2576 for (TileIndex cur_tile = *it; cur_tile != INVALID_TILE; cur_tile = ++it) {
2577 assert(IsInsideBS(TileX(cur_tile), perimeter_min_x, width));
2578 assert(IsInsideBS(TileY(cur_tile), perimeter_min_y, height));
2579 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) {
2580 Town *t = CalcClosestTownFromTile(cur_tile, mindist + 1);
2581 if (t == nullptr) continue;
2582
2583 uint dist = DistanceManhattan(t->xy, cur_tile);
2584 if (dist == mindist && t->index < nearest->index) nearest = t;
2585 if (dist < mindist) {
2586 nearest = t;
2587 mindist = dist;
2588 }
2589 }
2590 }
2591
2592 return nearest;
2593}
2594
2602static Town *AirportGetNearestTown(const Station *st, uint &mindist)
2603{
2605}
2606
2607
2610{
2611 for (Town *t : Town::Iterate()) t->noise_reached = 0;
2612
2613 for (const Station *st : Station::Iterate()) {
2614 if (st->airport.tile != INVALID_TILE && st->airport.type != AT_OILRIG) {
2615 uint dist;
2616 Town *nearest = AirportGetNearestTown(st, dist);
2617 nearest->noise_reached += GetAirportNoiseLevelForDistance(st->airport.GetSpec(), dist);
2618 }
2619 }
2620}
2621
2632CommandCost CmdBuildAirport(DoCommandFlags flags, TileIndex tile, uint8_t airport_type, uint8_t layout, StationID station_to_join, bool allow_adjacent)
2633{
2634 bool reuse = (station_to_join != NEW_STATION);
2635 if (!reuse) station_to_join = StationID::Invalid();
2636 bool distant_join = (station_to_join != StationID::Invalid());
2637
2638 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2639
2640 if (airport_type >= NUM_AIRPORTS) return CMD_ERROR;
2641
2643 if (ret.Failed()) return ret;
2644
2645 /* Check if a valid, buildable airport was chosen for construction */
2646 const AirportSpec *as = AirportSpec::Get(airport_type);
2647 if (!as->IsAvailable() || layout >= as->layouts.size()) return CMD_ERROR;
2648 if (!as->IsWithinMapBounds(layout, tile)) return CMD_ERROR;
2649
2650 Direction rotation = as->layouts[layout].rotation;
2651 int w = as->size_x;
2652 int h = as->size_y;
2653 if (rotation == Direction::E || rotation == Direction::W) std::swap(w, h);
2654 TileArea airport_area = TileArea(tile, w, h);
2655
2656 if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
2657 return CommandCost(STR_ERROR_STATION_TOO_SPREAD_OUT);
2658 }
2659
2660 AirportTileTableIterator tile_iter(as->layouts[layout].tiles, tile);
2661 CommandCost cost = CheckFlatLandAirport(tile_iter, flags);
2662 if (cost.Failed()) return cost;
2663
2664 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center. */
2665 uint dist;
2666 Town *nearest = AirportGetNearestTown(as, rotation, tile, std::move(tile_iter), dist);
2667 uint newnoise_level = GetAirportNoiseLevelForDistance(as, dist);
2668
2669 /* Check if local auth would allow a new airport */
2670 StringID authority_refuse_message = STR_NULL;
2671 Town *authority_refuse_town = nullptr;
2672
2673 if (_settings_game.economy.station_noise_level) {
2674 /* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
2675 if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
2676 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
2677 authority_refuse_town = nearest;
2678 }
2679 } else if (_settings_game.difficulty.town_council_tolerance != TOWN_COUNCIL_PERMISSIVE) {
2680 Town *t = ClosestTownFromTile(tile, UINT_MAX);
2681 uint num = 0;
2682 for (const Station *st : Station::Iterate()) {
2683 if (st->town == t && st->facilities.Test(StationFacility::Airport) && st->airport.type != AT_OILRIG) num++;
2684 }
2685 if (num >= 2) {
2686 authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
2687 authority_refuse_town = t;
2688 }
2689 }
2690
2691 if (authority_refuse_message != STR_NULL) {
2692 return CommandCostWithParam(authority_refuse_message, authority_refuse_town->index);
2693 }
2694
2695 Station *st = nullptr;
2696 ret = FindJoiningStation(StationID::Invalid(), station_to_join, allow_adjacent, airport_area, &st);
2697 if (ret.Failed()) return ret;
2698
2699 /* Distant join */
2700 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2701
2702 ret = BuildStationPart(&st, flags, reuse, airport_area, GetAirport(airport_type)->flags.Test(AirportFTAClass::Flag::Airplanes) ? StationNaming::Airport : StationNaming::Heliport);
2703 if (ret.Failed()) return ret;
2704
2705 if (st != nullptr && st->airport.tile != INVALID_TILE) {
2706 return CommandCost(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
2707 }
2708
2709 for (AirportTileTableIterator iter(as->layouts[layout].tiles, tile); iter != INVALID_TILE; ++iter) {
2711 }
2712
2713 if (flags.Test(DoCommandFlag::Execute)) {
2714 /* Always add the noise, so there will be no need to recalculate when option toggles */
2715 nearest->noise_reached += newnoise_level;
2716
2718 st->airport.type = airport_type;
2719 st->airport.layout = layout;
2720 st->airport.blocks = {};
2721 st->airport.rotation = rotation;
2722
2723 st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
2724
2725 for (AirportTileTableIterator iter(as->layouts[layout].tiles, tile); iter != INVALID_TILE; ++iter) {
2726 Tile t(iter);
2727 MakeAirport(t, st->owner, st->index, iter.GetStationGfx(), WaterClass::Invalid);
2728 SetStationTileRandomBits(t, GB(Random(), 0, 4));
2729 st->airport.Add(iter);
2730
2731 if (AirportTileSpec::Get(GetTranslatedAirportTileID(iter.GetStationGfx()))->animation.status != AnimationStatus::NoAnimation) AddAnimatedTile(t);
2732 }
2733
2734 /* Only call the animation trigger after all tiles have been built */
2735 for (AirportTileTableIterator iter(as->layouts[layout].tiles, tile); iter != INVALID_TILE; ++iter) {
2736 TriggerAirportTileAnimation(st, iter, AirportAnimationTrigger::Built);
2737 }
2738
2740
2741 Company::Get(st->owner)->infrastructure.airport++;
2742
2744 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2745
2746 if (_settings_game.economy.station_noise_level) {
2747 SetWindowDirty(WindowClass::TownView, nearest->index);
2748 }
2749 }
2750
2751 return cost;
2752}
2753
2760static CommandCost RemoveAirport(TileIndex tile, DoCommandFlags flags)
2761{
2762 Station *st = Station::GetByTile(tile);
2763
2765 CommandCost ret = CheckOwnership(st->owner);
2766 if (ret.Failed()) return ret;
2767 }
2768
2769 tile = st->airport.tile;
2770
2772
2773 for (const Aircraft *a : Aircraft::Iterate()) {
2774 if (!a->IsNormalAircraft()) continue;
2775 if (a->targetairport == st->index && a->state != FLYING) {
2776 return CommandCost(STR_ERROR_AIRCRAFT_IN_THE_WAY);
2777 }
2778 }
2779
2780 if (flags.Test(DoCommandFlag::Execute)) {
2781 for (uint i = 0; i < st->airport.GetNumHangars(); ++i) {
2782 TileIndex tile_cur = st->airport.GetHangarTile(i);
2783 OrderBackup::Reset(tile_cur, false);
2784 CloseWindowById(WindowClass::VehicleDepot, tile_cur);
2785 }
2786
2787 /* The noise level is the noise from the airport and reduce it to account for the distance to the town center.
2788 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
2789 * need of recalculation */
2790 uint dist;
2791 Town *nearest = AirportGetNearestTown(st, dist);
2793
2794 if (_settings_game.economy.station_noise_level) {
2795 SetWindowDirty(WindowClass::TownView, nearest->index);
2796 }
2797 }
2798
2799 for (TileIndex tile_cur : st->airport) {
2800 if (!st->TileBelongsToAirport(tile_cur)) continue;
2801
2802 CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
2803 if (ret.Failed()) return ret;
2804
2806
2807 if (flags.Test(DoCommandFlag::Execute)) {
2808 DoClearSquare(tile_cur);
2810 }
2811 }
2812
2813 if (flags.Test(DoCommandFlag::Execute)) {
2814 /* Clear the persistent storage. */
2815 delete st->airport.psa;
2816
2817 st->rect.AfterRemoveRect(st, st->airport);
2818
2819 st->airport.Clear();
2821 SetWindowClassesDirty(WindowClass::VehicleOrders);
2822
2823 InvalidateWindowData(WindowClass::StationView, st->index, -1);
2824
2825 Company::Get(st->owner)->infrastructure.airport--;
2826
2828
2830 }
2831
2832 return cost;
2833}
2834
2841CommandCost CmdOpenCloseAirport(DoCommandFlags flags, StationID station_id)
2842{
2843 if (!Station::IsValidID(station_id)) return CMD_ERROR;
2844 Station *st = Station::Get(station_id);
2845
2847
2848 CommandCost ret = CheckOwnership(st->owner);
2849 if (ret.Failed()) return ret;
2850
2851 if (flags.Test(DoCommandFlag::Execute)) {
2853 SetWindowWidgetDirty(WindowClass::StationView, st->index, WID_SV_CLOSE_AIRPORT);
2854 }
2855 return CommandCost();
2856}
2857
2865bool HasStationInUse(StationID station, bool include_company, CompanyID company)
2866{
2867 for (const OrderList *orderlist : OrderList::Iterate()) {
2868 const Vehicle *v = orderlist->GetFirstSharedVehicle();
2869 assert(v != nullptr);
2870 if ((v->owner == company) != include_company) continue;
2871
2872 for (const Order &order : orderlist->GetOrders()) {
2873 if (order.GetDestination() == station && (order.IsType(OT_GOTO_STATION) || order.IsType(OT_GOTO_WAYPOINT))) {
2874 return true;
2875 }
2876 }
2877 }
2878 return false;
2879}
2880
2883 {-1, 0},
2884 { 0, 0},
2885 { 0, 0},
2886 { 0, -1}
2887}}};
2888
2892
2901CommandCost CmdBuildDock(DoCommandFlags flags, TileIndex tile, StationID station_to_join, bool adjacent)
2902{
2903 bool reuse = (station_to_join != NEW_STATION);
2904 if (!reuse) station_to_join = StationID::Invalid();
2905 bool distant_join = (station_to_join != StationID::Invalid());
2906
2907 if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
2908
2910 if (direction == DiagDirection::Invalid) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2911 direction = ReverseDiagDir(direction);
2912
2913 /* Docks cannot be placed on rapids */
2914 if (HasTileWaterGround(tile)) return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2915
2917 if (ret.Failed()) return ret;
2918
2919 ret = IsDockBridgeAboveOk(tile, to_underlying(direction));
2920 if (ret.Failed()) return ret;
2921
2923 ret = Command<Commands::LandscapeClear>::Do(flags, tile);
2924 if (ret.Failed()) return ret;
2925 cost.AddCost(ret.GetCost());
2926
2927 TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
2928
2929 if (!HasTileWaterGround(tile_cur) || !IsTileFlat(tile_cur)) {
2930 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2931 }
2932
2934 if (ret.Failed()) return ret;
2935
2936 /* Get the water class of the water tile before it is cleared.*/
2937 WaterClass wc = GetWaterClass(tile_cur);
2938
2939 bool add_cost = !IsWaterTile(tile_cur);
2940 ret = Command<Commands::LandscapeClear>::Do(flags, tile_cur);
2941 if (ret.Failed()) return ret;
2942 if (add_cost) cost.AddCost(ret.GetCost());
2943
2944 tile_cur += TileOffsByDiagDir(direction);
2945 if (!IsTileType(tile_cur, TileType::Water) || !IsTileFlat(tile_cur)) {
2946 return CommandCost(STR_ERROR_SITE_UNSUITABLE);
2947 }
2948
2949 TileArea dock_area = TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
2950 _dock_w_chk[direction], _dock_h_chk[direction]);
2951
2952 /* middle */
2953 Station *st = nullptr;
2954 ret = FindJoiningStation(StationID::Invalid(), station_to_join, adjacent, dock_area, &st);
2955 if (ret.Failed()) return ret;
2956
2957 /* Distant join */
2958 if (st == nullptr && distant_join) st = Station::GetIfValid(station_to_join);
2959
2960 ret = BuildStationPart(&st, flags, reuse, dock_area, StationNaming::Dock);
2961 if (ret.Failed()) return ret;
2962
2963 if (flags.Test(DoCommandFlag::Execute)) {
2964 st->ship_station.Add(tile);
2965 TileIndex flat_tile = tile + TileOffsByDiagDir(direction);
2966 st->ship_station.Add(flat_tile);
2968
2969 st->rect.BeforeAddRect(dock_area.tile, dock_area.w, dock_area.h, StationRect::ADD_TRY);
2970
2971 /* If the water part of the dock is on a canal, update infrastructure counts.
2972 * This is needed as we've cleared that tile before.
2973 * Clearing object tiles may result in water tiles which are already accounted for in the water infrastructure total.
2974 * See: MakeWaterKeepingClass() */
2975 if (wc == WaterClass::Canal && !(HasTileWaterClass(flat_tile) && GetWaterClass(flat_tile) == WaterClass::Canal && IsTileOwner(flat_tile, _current_company))) {
2976 Company::Get(st->owner)->infrastructure.water++;
2977 }
2978 Company::Get(st->owner)->infrastructure.station += 2;
2979
2980 MakeDock(tile, st->owner, st->index, direction, wc);
2981 UpdateStationDockingTiles(st);
2982
2984 }
2985
2986 return cost;
2987}
2988
2989void RemoveDockingTile(TileIndex t)
2990{
2992 TileIndex tile = t + TileOffsByDiagDir(d);
2993 if (!IsValidTile(tile)) continue;
2994
2995 if (IsTileType(tile, TileType::Station)) {
2996 Station *st = Station::GetByTile(tile);
2997 if (st != nullptr) UpdateStationDockingTiles(st);
2998 } else if (IsTileType(tile, TileType::Industry)) {
3000 if (neutral != nullptr) UpdateStationDockingTiles(neutral);
3001 }
3002 }
3003}
3004
3011{
3012 assert(IsValidTile(tile));
3013
3014 /* Clear and maybe re-set docking tile */
3016 TileIndex docking_tile = tile + TileOffsByDiagDir(d);
3017 if (!IsValidTile(docking_tile)) continue;
3018
3019 if (IsPossibleDockingTile(docking_tile)) {
3020 SetDockingTile(docking_tile, false);
3021 CheckForDockingTile(docking_tile);
3022 }
3023 }
3024}
3025
3032{
3033 assert(IsDockTile(t));
3034
3035 StationGfx gfx = GetStationGfx(t);
3036 if (gfx < GFX_DOCK_BASE_WATER_PART) return t;
3037
3039 TileIndex tile = t + TileOffsByDiagDir(d);
3040 if (!IsValidTile(tile)) continue;
3041 if (!IsDockTile(tile)) continue;
3042 if (GetStationGfx(tile) < GFX_DOCK_BASE_WATER_PART && tile + TileOffsByDiagDir(GetDockDirection(tile)) == t) return tile;
3043 }
3044
3045 return INVALID_TILE;
3046}
3047
3054static CommandCost RemoveDock(TileIndex tile, DoCommandFlags flags)
3055{
3056 Station *st = Station::GetByTile(tile);
3057 CommandCost ret = CheckOwnership(st->owner);
3058 if (ret.Failed()) return ret;
3059
3060 if (!IsDockTile(tile)) return CMD_ERROR;
3061
3062 TileIndex tile1 = FindDockLandPart(tile);
3063 if (tile1 == INVALID_TILE) return CMD_ERROR;
3064 TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
3065
3066 ret = EnsureNoVehicleOnGround(tile1);
3067 if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
3068 if (ret.Failed()) return ret;
3069
3070 if (flags.Test(DoCommandFlag::Execute)) {
3071 DoClearSquare(tile1);
3072 MarkTileDirtyByTile(tile1);
3073 MakeWaterKeepingClass(tile2, st->owner);
3074
3075 st->rect.AfterRemoveTile(st, tile1);
3076 st->rect.AfterRemoveTile(st, tile2);
3077
3078 MakeShipStationAreaSmaller(st);
3079 if (st->ship_station.tile == INVALID_TILE) {
3080 st->ship_station.Clear();
3081 st->docking_station.Clear();
3083 SetWindowClassesDirty(WindowClass::VehicleOrders);
3084 }
3085
3086 Company::Get(st->owner)->infrastructure.station -= 2;
3087
3089
3092
3093 for (Ship *s : Ship::Iterate()) {
3094 /* Find all ships going to our dock. */
3095 if (s->current_order.GetDestination() != st->index) {
3096 continue;
3097 }
3098
3099 /* Find ships that are marked as "loading" but are no longer on a
3100 * docking tile. Force them to leave the station (as they were loading
3101 * on the removed dock). */
3102 if (s->current_order.IsType(OT_LOADING) && !(IsDockingTile(s->tile) && IsShipDestinationTile(s->tile, st->index))) {
3103 s->LeaveStation();
3104 }
3105
3106 /* If we no longer have a dock, mark the order as invalid and send
3107 * the ship to the next order (or, if there is none, make it
3108 * wander the world). */
3109 if (s->current_order.IsType(OT_GOTO_STATION) && !st->facilities.Test(StationFacility::Dock)) {
3110 s->SetDestTile(s->GetOrderStationLocation(st->index));
3111 }
3112 }
3113 }
3114
3116}
3117
3125{
3126 const auto &layouts = _station_display_datas[st];
3127 if (gfx >= layouts.size()) gfx &= 1;
3128 return layouts.data() + gfx;
3129}
3130
3140bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
3141{
3142 bool snow_desert;
3143 switch (*ground) {
3144 case SPR_RAIL_TRACK_X:
3145 case SPR_MONO_TRACK_X:
3146 case SPR_MGLV_TRACK_X:
3147 snow_desert = false;
3148 *overlay_offset = RTO_X;
3149 break;
3150
3151 case SPR_RAIL_TRACK_Y:
3152 case SPR_MONO_TRACK_Y:
3153 case SPR_MGLV_TRACK_Y:
3154 snow_desert = false;
3155 *overlay_offset = RTO_Y;
3156 break;
3157
3158 case SPR_RAIL_TRACK_X_SNOW:
3159 case SPR_MONO_TRACK_X_SNOW:
3160 case SPR_MGLV_TRACK_X_SNOW:
3161 snow_desert = true;
3162 *overlay_offset = RTO_X;
3163 break;
3164
3165 case SPR_RAIL_TRACK_Y_SNOW:
3166 case SPR_MONO_TRACK_Y_SNOW:
3167 case SPR_MGLV_TRACK_Y_SNOW:
3168 snow_desert = true;
3169 *overlay_offset = RTO_Y;
3170 break;
3171
3172 default:
3173 return false;
3174 }
3175
3176 if (ti != nullptr) {
3177 /* Decide snow/desert from tile */
3178 switch (_settings_game.game_creation.landscape) {
3180 snow_desert = (uint)ti->z > GetSnowLine() * TILE_HEIGHT;
3181 break;
3182
3184 snow_desert = GetTropicZone(ti->tile) == TropicZone::Desert;
3185 break;
3186
3187 default:
3188 break;
3189 }
3190 }
3191
3192 *ground = snow_desert ? SPR_FLAT_SNOW_DESERT_TILE : SPR_FLAT_GRASS_TILE;
3193 return true;
3194}
3195
3202static BridgePillarFlags GetStationBlockedPillars(std::span<const BridgeableTileInfo> bridgeable_info, uint8_t layout)
3203{
3204 if (layout < std::size(bridgeable_info)) return bridgeable_info[layout].disallowed_pillars;
3205 return BRIDGEPILLARFLAGS_ALL;
3206}
3207
3217{
3218 if (statspec == nullptr || !statspec->flags.Test(StationSpecFlag::CustomFoundations)) return false;
3219
3220 /* Station has custom foundations.
3221 * Check whether the foundation continues beyond the tile's upper sides. */
3222 uint edge_info = 0;
3223 auto [slope, z] = GetFoundationPixelSlope(ti->tile);
3224 if (!HasFoundationNW(ti->tile, slope, z)) SetBit(edge_info, 0);
3225 if (!HasFoundationNE(ti->tile, slope, z)) SetBit(edge_info, 1);
3226
3227 SpriteID image = GetCustomStationFoundationRelocation(statspec, st, ti->tile, gfx, edge_info);
3228 if (image == 0) return false;
3229
3231 /* Station provides extended foundations. */
3232 static constexpr uint8_t foundation_parts[] = {
3233 UINT8_MAX, UINT8_MAX, UINT8_MAX, 0, // Invalid, Invalid, Invalid, SLOPE_SW
3234 UINT8_MAX, 1, 2, 3, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3235 UINT8_MAX, 4, 5, 6, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3236 7, 8, 9, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3237 };
3238 assert(ti->tileh < std::size(foundation_parts));
3239 if (foundation_parts[ti->tileh] == UINT8_MAX) return false;
3240
3241 AddSortableSpriteToDraw(image + foundation_parts[ti->tileh], PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3242 } else {
3243 /* Draw simple foundations, built up from 8 possible foundation sprites.
3244 * Each set bit represents one of the eight composite sprites to be drawn.
3245 * 'Invalid' entries will not drawn but are included for completeness. */
3246 static constexpr uint8_t composite_foundation_parts[] = {
3247 0b0000'0000, 0b1101'0001, 0b1110'0100, 0b1110'0000, // Invalid, Invalid, Invalid, SLOPE_SW
3248 0b1100'1010, 0b1100'1001, 0b1100'0100, 0b1100'0000, // Invalid, SLOPE_EW, SLOPE_SE, SLOPE_WSE
3249 0b1101'0010, 0b1001'0001, 0b1110'0100, 0b1010'0000, // Invalid, SLOPE_NW, SLOPE_NS, SLOPE_NWS
3250 0b0100'1010, 0b0000'1001, 0b0100'0100, // SLOPE_NE, SLOPE_ENW, SLOPE_SEN
3251 };
3252 assert(ti->tileh < std::size(composite_foundation_parts));
3253
3254 uint8_t parts = composite_foundation_parts[ti->tileh];
3255
3256 /* If foundations continue beyond the tile's upper sides then mask out the last two pieces. */
3257 if (HasBit(edge_info, 0)) ClrBit(parts, 6);
3258 if (HasBit(edge_info, 1)) ClrBit(parts, 7);
3259
3260 /* We always have to draw at least one sprite, so if we have no parts to draw fall back to default foundation. */
3261 if (parts == 0) return false;
3262
3264 for (uint i : SetBitIterator(parts)) {
3265 AddSortableSpriteToDraw(image + i, PAL_NONE, *ti, {{}, {TILE_SIZE, TILE_SIZE, TILE_HEIGHT - 1}, {}});
3266 }
3268 }
3269
3270 OffsetGroundSprite(0, -static_cast<int>(TILE_HEIGHT));
3272
3273 return true;
3274}
3275
3278{
3279 const NewGRFSpriteLayout *layout = nullptr;
3280 SpriteLayoutProcessor processor; // owns heap, borrowed by tmp_layout and t
3281 DrawTileSpriteSpan tmp_layout;
3282 const DrawTileSprites *t = nullptr;
3283 int32_t total_offset;
3284 const RailTypeInfo *rti = nullptr;
3285 uint32_t relocation = 0;
3286 uint32_t ground_relocation = 0;
3287 BaseStation *st = nullptr;
3288 const StationSpec *statspec = nullptr;
3289 uint tile_layout = 0;
3290 auto bridgeable_info = GetStationBridgeableTileInfo(GetStationType(ti->tile));
3291
3292 if (HasStationRail(ti->tile)) {
3293 rti = GetRailTypeInfo(GetRailType(ti->tile));
3294 total_offset = rti->GetRailtypeSpriteOffset();
3295
3296 if (IsCustomStationSpecIndex(ti->tile)) {
3297 /* look for customization */
3298 st = BaseStation::GetByTile(ti->tile);
3299 statspec = st->speclist[GetCustomStationSpecIndex(ti->tile)].spec;
3300
3301 if (statspec != nullptr) {
3302 tile_layout = GetStationGfx(ti->tile);
3303
3305 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, st, ti->tile);
3306 if (callback != CALLBACK_FAILED) tile_layout = (callback & ~1) + to_underlying(GetRailStationAxis(ti->tile));
3307 }
3308
3309 /* Ensure the chosen tile layout is valid for this custom station */
3310 if (!statspec->renderdata.empty()) {
3311 layout = &statspec->renderdata[tile_layout < statspec->renderdata.size() ? tile_layout : (uint)GetRailStationAxis(ti->tile)];
3312 if (!layout->NeedsPreprocessing()) {
3313 t = layout;
3314 layout = nullptr;
3315 }
3316 }
3317 }
3318 }
3319 if (statspec != nullptr) bridgeable_info = statspec->bridgeable_info;
3320 } else {
3321 total_offset = 0;
3322 }
3323
3324 StationGfx gfx = GetStationGfx(ti->tile);
3325 if (IsAirport(ti->tile)) {
3326 gfx = GetAirportGfx(ti->tile);
3327 if (gfx >= NEW_AIRPORTTILE_OFFSET) {
3328 const AirportTileSpec *ats = AirportTileSpec::Get(gfx);
3329 if (ats->grf_prop.HasSpriteGroups() && DrawNewAirportTile(ti, Station::GetByTile(ti->tile), ats)) {
3330 return;
3331 }
3332 /* No sprite group (or no valid one) found, meaning no graphics associated.
3333 * Use the substitute one instead */
3334 assert(ats->grf_prop.subst_id != INVALID_AIRPORTTILE);
3335 gfx = ats->grf_prop.subst_id;
3336 }
3337 switch (gfx) {
3338 case APT_RADAR_GRASS_FENCE_SW:
3339 t = &_station_display_datas_airport_radar_grass_fence_sw[GetAnimationFrame(ti->tile)];
3340 break;
3341 case APT_GRASS_FENCE_NE_FLAG:
3342 t = &_station_display_datas_airport_flag_grass_fence_ne[GetAnimationFrame(ti->tile)];
3343 break;
3344 case APT_RADAR_FENCE_SW:
3345 t = &_station_display_datas_airport_radar_fence_sw[GetAnimationFrame(ti->tile)];
3346 break;
3347 case APT_RADAR_FENCE_NE:
3348 t = &_station_display_datas_airport_radar_fence_ne[GetAnimationFrame(ti->tile)];
3349 break;
3350 case APT_GRASS_FENCE_NE_FLAG_2:
3351 t = &_station_display_datas_airport_flag_grass_fence_ne_2[GetAnimationFrame(ti->tile)];
3352 break;
3353 }
3354 }
3355
3356 Owner owner = GetTileOwner(ti->tile);
3357
3358 PaletteID palette;
3359 if (Company::IsValidID(owner)) {
3360 palette = GetCompanyPalette(owner);
3361 } else {
3362 /* Some stations are not owner by a company, namely oil rigs */
3363 palette = PALETTE_TO_GREY;
3364 }
3365
3366 if (layout == nullptr && t == nullptr) t = GetStationTileLayout(GetStationType(ti->tile), gfx);
3367
3368 /* don't show foundation for docks */
3369 if (ti->tileh != SLOPE_FLAT && !IsDock(ti->tile)) {
3370 if (!DrawCustomStationFoundations(statspec, st, ti, tile_layout)) {
3372 }
3373 }
3374
3375 bool draw_ground = false;
3376
3377 if (IsBuoy(ti->tile)) {
3378 DrawWaterClassGround(ti);
3379 SpriteID sprite = GetCanalSprite(CF_BUOY, ti->tile);
3380 if (sprite != 0) total_offset = sprite - SPR_IMG_BUOY;
3381 } else if (IsDock(ti->tile) || (IsOilRig(ti->tile) && IsTileOnWater(ti->tile))) {
3382 if (ti->tileh == SLOPE_FLAT) {
3383 DrawWaterClassGround(ti);
3384 } else {
3385 assert(IsDock(ti->tile));
3386 TileIndex water_tile = ti->tile + TileOffsByDiagDir(GetDockDirection(ti->tile));
3387 WaterClass wc = HasTileWaterClass(water_tile) ? GetWaterClass(water_tile) : WaterClass::Invalid;
3388 if (wc == WaterClass::Sea) {
3389 DrawShoreTile(ti->tileh);
3390 } else {
3391 DrawClearLandTile(ti, 3);
3392 }
3393 }
3394 } else if (IsRoadWaypointTile(ti->tile)) {
3396 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3397 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3398 RoadBits road = (road_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3399 RoadBits tram = (tram_rt != INVALID_ROADTYPE) ? bits : RoadBits{};
3400 const RoadTypeInfo *road_rti = (road_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(road_rt) : nullptr;
3401 const RoadTypeInfo *tram_rti = (tram_rt != INVALID_ROADTYPE) ? GetRoadTypeInfo(tram_rt) : nullptr;
3402
3403 if (ti->tileh != SLOPE_FLAT) {
3405 }
3406
3407 DrawRoadGroundSprites(ti, road, tram, road_rti, tram_rti, GetRoadWaypointRoadside(ti->tile), IsRoadWaypointOnSnowOrDesert(ti->tile));
3408 } else {
3409 if (layout != nullptr) {
3410 /* Sprite layout which needs preprocessing */
3411 bool separate_ground = statspec->flags.Test(StationSpecFlag::SeparateGround);
3412 processor = SpriteLayoutProcessor(*layout, total_offset, rti->fallback_railtype, 0, 0, separate_ground);
3413 GetCustomStationRelocation(processor, statspec, st, ti->tile);
3414 tmp_layout = processor.GetLayout();
3415 t = &tmp_layout;
3416 total_offset = 0;
3417 } else if (statspec != nullptr) {
3418 /* Simple sprite layout */
3419 ground_relocation = relocation = GetCustomStationRelocation(statspec, st, ti->tile, 0);
3421 ground_relocation = GetCustomStationRelocation(statspec, st, ti->tile, 1);
3422 }
3423 ground_relocation += rti->fallback_railtype;
3424 }
3425
3426 draw_ground = true;
3427 }
3428
3429 if (draw_ground && !IsAnyRoadStop(ti->tile)) {
3430 SpriteID image = t->ground.sprite;
3431 PaletteID pal = t->ground.pal;
3432 RailTrackOffset overlay_offset;
3433 if (rti != nullptr && rti->UsesOverlay() && SplitGroundSpriteForOverlay(ti, &image, &overlay_offset)) {
3435 DrawGroundSprite(image, PAL_NONE);
3436 DrawGroundSprite(ground + overlay_offset, PAL_NONE);
3437
3438 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationReservation(ti->tile)) {
3440 DrawGroundSprite(overlay + overlay_offset, PALETTE_CRASH);
3441 }
3442 } else {
3443 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3444 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3445 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3446
3447 /* PBS debugging, draw reserved tracks darker */
3448 if (_game_mode != GameMode::Menu && _settings_client.gui.show_track_reservation && HasStationRail(ti->tile) && HasStationReservation(ti->tile)) {
3450 }
3451 }
3452 }
3453
3455
3456 if (IsAnyRoadStop(ti->tile)) {
3457 RoadType road_rt = GetRoadTypeRoad(ti->tile);
3458 RoadType tram_rt = GetRoadTypeTram(ti->tile);
3459 const RoadTypeInfo *road_rti = road_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(road_rt);
3460 const RoadTypeInfo *tram_rti = tram_rt == INVALID_ROADTYPE ? nullptr : GetRoadTypeInfo(tram_rt);
3461
3462 StationGfx view = GetStationGfx(ti->tile);
3463 StationType type = GetStationType(ti->tile);
3464
3465 const RoadStopSpec *stopspec = GetRoadStopSpec(ti->tile);
3466 RoadStopDrawModes stop_draw_mode{};
3467 if (stopspec != nullptr) {
3468 stop_draw_mode = stopspec->draw_mode;
3469 st = BaseStation::GetByTile(ti->tile);
3470 std::array<int32_t, 1> regs100;
3471 auto result = GetRoadStopLayout(ti, stopspec, st, type, view, regs100);
3472 if (result.has_value()) {
3473 if (stopspec->flags.Test(RoadStopSpecFlag::DrawModeRegister)) {
3474 stop_draw_mode = static_cast<RoadStopDrawModes>(regs100[0]);
3475 }
3476 if (type == StationType::RoadWaypoint && stop_draw_mode.Test(RoadStopDrawMode::WaypGround)) {
3477 draw_ground = true;
3478 }
3479 processor = std::move(*result);
3480 tmp_layout = processor.GetLayout();
3481 t = &tmp_layout;
3482 }
3483 }
3484
3485 /* Draw ground sprite */
3486 if (draw_ground) {
3487 SpriteID image = t->ground.sprite;
3488 PaletteID pal = t->ground.pal;
3489 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
3490 if (GB(image, 0, SPRITE_WIDTH) != 0) {
3491 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
3492 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
3493 }
3494 }
3495
3496 if (IsDriveThroughStopTile(ti->tile)) {
3497 if (type != StationType::RoadWaypoint && (stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Overlay))) {
3498 uint sprite_offset = GetDriveThroughStopAxis(ti->tile) == Axis::X ? 1 : 0;
3499 DrawRoadOverlays(ti, PAL_NONE, road_rti, tram_rti, sprite_offset, sprite_offset);
3500 }
3501 } else {
3502 /* Non-drivethrough road stops are only valid for roads. */
3503 assert(road_rt != INVALID_ROADTYPE && tram_rt == INVALID_ROADTYPE);
3504
3505 if ((stopspec == nullptr || stop_draw_mode.Test(RoadStopDrawMode::Road)) && road_rti->UsesOverlay()) {
3507 DrawGroundSprite(ground + view, PAL_NONE);
3508 }
3509 }
3510 if (stopspec != nullptr) bridgeable_info = stopspec->bridgeable_info;
3511
3512 if (stopspec == nullptr || !stopspec->flags.Test(RoadStopSpecFlag::NoCatenary)) {
3513 /* Draw road, tram catenary */
3514 DrawRoadCatenary(ti);
3515 }
3516 }
3517
3518 if (IsRailWaypoint(ti->tile)) {
3519 /* Don't offset the waypoint graphics; they're always the same. */
3520 total_offset = 0;
3521 }
3522
3523 DrawRailTileSeq(ti, t, TransparencyOption::Buildings, total_offset, relocation, palette);
3524 DrawBridgeMiddle(ti, GetStationBlockedPillars(bridgeable_info, GetStationGfx(ti->tile)));
3525}
3526
3527void StationPickerDrawSprite(int x, int y, StationType st, RailType railtype, RoadType roadtype, int image)
3528{
3529 int32_t total_offset = 0;
3531 const DrawTileSprites *t = GetStationTileLayout(st, image);
3532 const RailTypeInfo *railtype_info = nullptr;
3533
3534 if (railtype != INVALID_RAILTYPE) {
3535 railtype_info = GetRailTypeInfo(railtype);
3536 total_offset = railtype_info->GetRailtypeSpriteOffset();
3537 }
3538
3539 SpriteID img = t->ground.sprite;
3540 RailTrackOffset overlay_offset;
3541 if (railtype_info != nullptr && railtype_info->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &img, &overlay_offset)) {
3543 DrawSprite(img, PAL_NONE, x, y);
3544 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
3545 } else {
3546 DrawSprite(img + total_offset, HasBit(img, PALETTE_MODIFIER_COLOUR) ? pal : PAL_NONE, x, y);
3547 }
3548
3549 if (roadtype != INVALID_ROADTYPE) {
3550 const RoadTypeInfo *roadtype_info = GetRoadTypeInfo(roadtype);
3551 if (image >= 4) {
3552 /* Drive-through stop */
3553 uint sprite_offset = 5 - image;
3554
3555 /* Road underlay takes precedence over tram */
3556 if (roadtype_info->UsesOverlay()) {
3558 DrawSprite(ground + sprite_offset, PAL_NONE, x, y);
3559
3561 if (overlay) DrawSprite(overlay + sprite_offset, PAL_NONE, x, y);
3562 } else if (RoadTypeIsTram(roadtype)) {
3563 DrawSprite(SPR_TRAMWAY_TRAM + sprite_offset, PAL_NONE, x, y);
3564 }
3565 } else {
3566 /* Bay stop */
3567 if (RoadTypeIsRoad(roadtype) && roadtype_info->UsesOverlay()) {
3569 DrawSprite(ground + image, PAL_NONE, x, y);
3570 }
3571 }
3572 }
3573
3574 /* Default waypoint has no railtype specific sprites */
3575 DrawRailTileSeqInGUI(x, y, t, (st == StationType::RailWaypoint || st == StationType::RoadWaypoint) ? 0 : total_offset, 0, pal);
3576}
3577
3578
3579static void FillTileDescRoadStop(TileIndex tile, TileDesc &td)
3580{
3581 RoadType road_rt = GetRoadTypeRoad(tile);
3582 RoadType tram_rt = GetRoadTypeTram(tile);
3583 Owner road_owner = INVALID_OWNER;
3584 Owner tram_owner = INVALID_OWNER;
3585 if (road_rt != INVALID_ROADTYPE) {
3586 const RoadTypeInfo *rti = GetRoadTypeInfo(road_rt);
3587 td.roadtype = rti->strings.name;
3588 td.road_speed = rti->max_speed / 2;
3589 road_owner = GetRoadOwner(tile, RoadTramType::Road);
3590 }
3591
3592 if (tram_rt != INVALID_ROADTYPE) {
3593 const RoadTypeInfo *rti = GetRoadTypeInfo(tram_rt);
3594 td.tramtype = rti->strings.name;
3595 td.tram_speed = rti->max_speed / 2;
3596 tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
3597 }
3598
3599 if (IsDriveThroughStopTile(tile)) {
3600 /* Is there a mix of owners? */
3601 if ((tram_owner != INVALID_OWNER && tram_owner != td.owner[0]) ||
3602 (road_owner != INVALID_OWNER && road_owner != td.owner[0])) {
3603 uint i = 1;
3604 if (road_owner != INVALID_OWNER) {
3605 td.owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
3606 td.owner[i] = road_owner;
3607 i++;
3608 }
3609 if (tram_owner != INVALID_OWNER) {
3610 td.owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
3611 td.owner[i] = tram_owner;
3612 }
3613 }
3614 }
3615}
3616
3617void FillTileDescRailStation(TileIndex tile, TileDesc &td)
3618{
3619 const StationSpec *spec = GetStationSpec(tile);
3620
3621 if (spec != nullptr) {
3623 td.station_name = spec->name;
3624
3625 if (spec->grf_prop.HasGrfFile()) {
3626 const GRFConfig *gc = GetGRFConfig(spec->grf_prop.grfid);
3627 td.grf = gc->GetName();
3628 }
3629 }
3630
3631 const RailTypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
3632 td.rail_speed = rti->max_speed;
3633 td.railtype = rti->strings.name;
3634}
3635
3636void FillTileDescAirport(TileIndex tile, TileDesc &td)
3637{
3638 const AirportSpec *as = Station::GetByTile(tile)->airport.GetSpec();
3640 td.airport_name = as->name;
3641
3642 const AirportTileSpec *ats = AirportTileSpec::GetByTile(tile);
3643 td.airport_tile_name = ats->name;
3644
3645 if (as->grf_prop.HasGrfFile()) {
3646 const GRFConfig *gc = GetGRFConfig(as->grf_prop.grfid);
3647 td.grf = gc->GetName();
3648 } else if (ats->grf_prop.HasGrfFile()) {
3649 const GRFConfig *gc = GetGRFConfig(ats->grf_prop.grfid);
3650 td.grf = gc->GetName();
3651 }
3652}
3653
3656{
3657 td.owner[0] = GetTileOwner(tile);
3659
3660 if (IsAnyRoadStop(tile)) FillTileDescRoadStop(tile, td);
3661 if (HasStationRail(tile)) FillTileDescRailStation(tile, td);
3662 if (IsAirport(tile)) FillTileDescAirport(tile, td);
3663
3664 StringID str;
3665 switch (GetStationType(tile)) {
3666 default: NOT_REACHED();
3667 case StationType::Rail: str = STR_LAI_STATION_DESCRIPTION_RAILROAD_STATION; break;
3669 str = (IsHangar(tile) ? STR_LAI_STATION_DESCRIPTION_AIRCRAFT_HANGAR : STR_LAI_STATION_DESCRIPTION_AIRPORT);
3670 break;
3671 case StationType::Truck: str = STR_LAI_STATION_DESCRIPTION_TRUCK_LOADING_AREA; break;
3672 case StationType::Bus: str = STR_LAI_STATION_DESCRIPTION_BUS_STATION; break;
3673 case StationType::Oilrig: {
3674 const Industry *i = Station::GetByTile(tile)->industry;
3675 const IndustrySpec *is = GetIndustrySpec(i->type);
3676 td.owner[0] = i->owner;
3677 str = is->name;
3678 if (is->grf_prop.HasGrfFile()) td.grf = GetGRFConfig(is->grf_prop.grfid)->GetName();
3679 break;
3680 }
3681 case StationType::Dock: str = STR_LAI_STATION_DESCRIPTION_SHIP_DOCK; break;
3682 case StationType::Buoy: str = STR_LAI_STATION_DESCRIPTION_BUOY; break;
3683 case StationType::RailWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3684 case StationType::RoadWaypoint: str = STR_LAI_STATION_DESCRIPTION_WAYPOINT; break;
3685 }
3686 td.str = str;
3687}
3688
3689
3692{
3693 TrackBits trackbits = TRACK_BIT_NONE;
3694
3695 switch (mode) {
3696 case TRANSPORT_RAIL:
3697 if (HasStationRail(tile) && !IsStationTileBlocked(tile)) {
3698 trackbits = TrackToTrackBits(GetRailStationTrack(tile));
3699 }
3700 break;
3701
3702 case TRANSPORT_WATER:
3703 /* buoy is coded as a station, it is always on open water */
3704 if (IsBuoy(tile)) {
3705 trackbits = TRACK_BIT_ALL;
3706 /* remove tracks that connect NE map edge */
3707 if (TileX(tile) == 0) trackbits &= ~(TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT);
3708 /* remove tracks that connect NW map edge */
3709 if (TileY(tile) == 0) trackbits &= ~(TRACK_BIT_Y | TRACK_BIT_LEFT | TRACK_BIT_UPPER);
3710 }
3711 break;
3712
3713 case TRANSPORT_ROAD:
3714 if (IsAnyRoadStop(tile)) {
3715 RoadTramType rtt = (RoadTramType)sub_mode;
3716 if (!HasTileRoadType(tile, rtt)) break;
3717
3718 if (IsBayRoadStopTile(tile)) {
3719 DiagDirection dir = GetBayRoadStopDir(tile);
3720 if (side != DiagDirection::Invalid && dir != side) break;
3721 trackbits = DiagDirToDiagTrackBits(dir);
3722 } else {
3723 Axis axis = GetDriveThroughStopAxis(tile);
3724 if (side != DiagDirection::Invalid && axis != DiagDirToAxis(side)) break;
3725 trackbits = AxisToTrackBits(axis);
3726 }
3727 }
3728 break;
3729
3730 default:
3731 break;
3732 }
3733
3734 return {TrackBitsToTrackdirBits(trackbits), TRACKDIR_BIT_NONE};
3735}
3736
3737
3740{
3741 auto *st = BaseStation::GetByTile(tile);
3742 switch (GetStationType(tile)) {
3744 TriggerAirportTileAnimation(Station::From(st), tile, AirportAnimationTrigger::TileLoop);
3745 break;
3746
3747 case StationType::Rail:
3749 TriggerStationAnimation(st, tile, StationAnimationTrigger::TileLoop);
3750 break;
3751
3752 case StationType::Dock:
3753 if (!IsTileFlat(tile)) break; // only handle water part
3754 [[fallthrough]];
3755
3756 case StationType::Oilrig: //(station part)
3757 case StationType::Buoy:
3758 TileLoop_Water(tile);
3759 break;
3760
3761 case StationType::Truck:
3762 case StationType::Bus:
3763 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3764 break;
3765
3767 switch (_settings_game.game_creation.landscape) {
3769 if (IsRoadWaypointOnSnowOrDesert(tile) != (GetTileZ(tile) > GetSnowLine())) {
3771 MarkTileDirtyByTile(tile);
3772 }
3773 break;
3774
3778 MarkTileDirtyByTile(tile);
3779 }
3780 break;
3781
3782 default: break;
3783 }
3784
3785 HouseZone new_zone = HouseZone::TownEdge;
3786 const Town *t = ClosestTownFromTile(tile, UINT_MAX);
3787 if (t != nullptr) {
3788 new_zone = GetTownRadiusGroup(t, tile);
3789 }
3790
3791 /* Adjust road ground type depending on 'new_zone' */
3793 Roadside cur_rs = GetRoadWaypointRoadside(tile);
3794
3795 if (new_rs != cur_rs) {
3796 SetRoadWaypointRoadside(tile, cur_rs == Roadside::Barren ? new_rs : Roadside::Barren);
3797 MarkTileDirtyByTile(tile);
3798 }
3799
3800 TriggerRoadStopAnimation(st, tile, StationAnimationTrigger::TileLoop);
3801 break;
3802 }
3803
3804 default: break;
3805 }
3806}
3807
3808
3811{
3812 if (HasStationRail(tile)) {
3813 AnimateStationTile(tile);
3814 return;
3815 }
3816
3817 if (IsAirport(tile)) {
3818 AnimateAirportTile(tile);
3819 return;
3820 }
3821
3822 if (IsAnyRoadStopTile(tile)) {
3823 AnimateRoadStopTile(tile);
3824 return;
3825 }
3826}
3827
3828
3831{
3832 const BaseStation *bst = BaseStation::GetByTile(tile);
3833
3836 } else if (IsHangar(tile)) {
3837 const Station *st = Station::From(bst);
3839 } else {
3840 ShowStationViewWindow(bst->index);
3841 }
3842 return true;
3843}
3844
3846static VehicleEnterTileStates VehicleEnterTile_Station(Vehicle *v, TileIndex tile, int x, int y)
3847{
3848 if (v->type == VehicleType::Train) {
3849 StationID station_id = GetStationIndex(tile);
3850 if (!IsRailStation(tile) || !v->IsMovingFront()) return {};
3851 Vehicle *consist = v->First();
3852 if (!consist->current_order.ShouldStopAtStation(consist, station_id)) return {};
3853
3854 int station_ahead;
3855 int station_length;
3856 int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
3857
3858 /* Stop whenever that amount of station ahead + the distance from the
3859 * begin of the platform to the stop location is longer than the length
3860 * of the platform. Station ahead 'includes' the current tile where the
3861 * vehicle is on, so we need to subtract that. */
3862 if (stop + station_ahead - (int)TILE_SIZE >= station_length) return {};
3863
3865
3866 x &= 0xF;
3867 y &= 0xF;
3868
3869 if (DiagDirToAxis(dir) != Axis::X) std::swap(x, y);
3870 if (y == TILE_SIZE / 2) {
3871 if (dir != DiagDirection::SE && dir != DiagDirection::SW) x = TILE_SIZE - 1 - x;
3872 stop &= TILE_SIZE - 1;
3873
3874 if (x == stop) {
3875 return VehicleEnterTileState::EnteredStation; // enter station
3876 } else if (x < stop) {
3878 uint16_t spd = std::max(0, (stop - x) * 20 - 15);
3879 if (spd < v->cur_speed) v->cur_speed = spd;
3880 }
3881 }
3882 } else if (v->type == VehicleType::Road) {
3884 if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
3885 if (IsStationRoadStop(tile) && rv->IsFrontEngine()) {
3886 /* Attempt to allocate a parking bay in a road stop */
3887 if (RoadStop::GetByTile(tile, GetRoadStopType(tile))->Enter(rv)) return {};
3889 }
3890 }
3891 }
3892
3893 return {};
3894}
3895
3901{
3902 /* Collect cargoes accepted since the last big tick. */
3903 CargoTypes cargoes{};
3904 for (CargoType cargo_type{}; cargo_type < NUM_CARGO; ++cargo_type) {
3905 if (st->goods[cargo_type].status.Test(GoodsEntry::State::AcceptedBigtick)) cargoes.Set(cargo_type);
3906 }
3907
3908 /* Anything to do? */
3909 if (cargoes.None()) return;
3910
3911 /* Loop over all houses in the catchment. */
3913 for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
3914 if (IsTileType(tile, TileType::House)) {
3916 }
3917 }
3918}
3919
3927{
3928 if (!st->IsInUse()) {
3929 if (++st->delete_ctr >= 8) delete st;
3930 return false;
3931 }
3932
3933 if (Station::IsExpected(st)) {
3935
3936 for (GoodsEntry &ge : Station::From(st)->goods) {
3938 }
3939 }
3940
3941
3943
3944 return true;
3945}
3946
3947static inline void byte_inc_sat(uint8_t *p)
3948{
3949 uint8_t b = *p + 1;
3950 if (b != 0) *p = b;
3951}
3952
3959static void TruncateCargo(const CargoSpec *cs, GoodsEntry *ge, uint amount = UINT_MAX)
3960{
3961 /* If truncating also punish the source stations' ratings to
3962 * decrease the flow of incoming cargo. */
3963
3964 if (!ge->HasData()) return;
3965
3966 StationCargoAmountMap waiting_per_source;
3967 ge->GetData().cargo.Truncate(amount, &waiting_per_source);
3968 for (StationCargoAmountMap::iterator i(waiting_per_source.begin()); i != waiting_per_source.end(); ++i) {
3969 Station *source_station = Station::GetIfValid(i->first);
3970 if (source_station == nullptr) continue;
3971
3972 GoodsEntry &source_ge = source_station->goods[cs->Index()];
3973 source_ge.max_waiting_cargo = std::max(source_ge.max_waiting_cargo, i->second);
3974 }
3975}
3976
3982{
3983 bool waiting_changed = false;
3984
3985 byte_inc_sat(&st->time_since_load);
3986 byte_inc_sat(&st->time_since_unload);
3987
3988 for (const CargoSpec *cs : CargoSpec::Iterate()) {
3989 GoodsEntry *ge = &st->goods[cs->Index()];
3990
3991 /* The station might not currently be moving this cargo. */
3992 if (!ge->HasRating()) {
3993 /* Slowly increase the rating back to its original level in the case we
3994 * didn't deliver cargo yet to this station. This happens when a bribe
3995 * failed while you didn't moved that cargo yet to a station. */
3996 if (ge->rating < INITIAL_STATION_RATING) ge->rating++;
3997
3998 /* Nothing else to do with this cargo. */
3999 continue;
4000 }
4001
4002 byte_inc_sat(&ge->time_since_pickup);
4003
4004 /* If this cargo hasn't been picked up in a long time, get rid of it. */
4005 if (ge->time_since_pickup == 255 && _settings_game.order.selectgoods) {
4007 ge->last_speed = 0;
4008 TruncateCargo(cs, ge);
4009 waiting_changed = true;
4010 continue;
4011 }
4012
4013 bool skip = false;
4014 int rating = 0;
4015 uint waiting = ge->AvailableCount();
4016
4017 /* num_dests is at least 1 if there is any cargo as
4018 * StationID::Invalid() is also a destination.
4019 */
4020 uint num_dests = ge->HasData() ? static_cast<uint>(ge->GetData().cargo.Packets()->MapSize()) : 0;
4021
4022 /* Average amount of cargo per next hop, but prefer solitary stations
4023 * with only one or two next hops. They are allowed to have more
4024 * cargo waiting per next hop.
4025 * With manual cargo distribution waiting_avg = waiting / 2 as then
4026 * StationID::Invalid() is the only destination.
4027 */
4028 uint waiting_avg = waiting / (num_dests + 1);
4029
4030 if (_cheats.station_rating.value) {
4031 ge->rating = rating = MAX_STATION_RATING;
4032 skip = true;
4033 } else if (cs->callback_mask.Test(CargoCallbackMask::StationRatingCalc)) {
4034 /* Perform custom station rating. If it succeeds the speed, days in transit and
4035 * waiting cargo ratings must not be executed. */
4036
4037 /* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
4038 uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
4039
4040 uint32_t var18 = ClampTo<uint8_t>(ge->time_since_pickup)
4042 | (ClampTo<uint8_t>(last_speed) << 24);
4043 /* Convert to the 'old' vehicle types */
4044 uint32_t var10 = (st->last_vehicle_type == VehicleType::Invalid) ? 0x0 : (to_underlying(st->last_vehicle_type) + 0x10);
4045 uint16_t callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
4046 if (callback != CALLBACK_FAILED) {
4047 skip = true;
4048 rating = GB(callback, 0, 14);
4049
4050 /* Simulate a 15 bit signed value */
4051 if (HasBit(callback, 14)) rating -= 0x4000;
4052 }
4053 }
4054
4055 if (!skip) {
4056 int b = ge->last_speed - 85;
4057 if (b >= 0) rating += b >> 2;
4058
4059 uint8_t waittime = ge->time_since_pickup;
4060 if (st->last_vehicle_type == VehicleType::Ship) waittime >>= 2;
4061 if (waittime <= 21) rating += 25;
4062 if (waittime <= 12) rating += 25;
4063 if (waittime <= 6) rating += 45;
4064 if (waittime <= 3) rating += 35;
4065
4066 rating -= 90;
4067 if (ge->max_waiting_cargo <= 1500) rating += 55;
4068 if (ge->max_waiting_cargo <= 1000) rating += 35;
4069 if (ge->max_waiting_cargo <= 600) rating += 10;
4070 if (ge->max_waiting_cargo <= 300) rating += 20;
4071 if (ge->max_waiting_cargo <= 100) rating += 10;
4072 }
4073
4074 if (Company::IsValidID(st->owner) && st->town->statues.Test(st->owner)) rating += 26;
4075
4076 uint8_t age = ge->last_age;
4077 if (age < 3) rating += 10;
4078 if (age < 2) rating += 10;
4079 if (age < 1) rating += 13;
4080
4081 {
4082 int or_ = ge->rating; // old rating
4083
4084 /* only modify rating in steps of -2, -1, 0, 1 or 2 */
4085 ge->rating = rating = ClampTo<uint8_t>(or_ + Clamp(rating - or_, -2, 2));
4086
4087 /* if rating is <= 64 and more than 100 items waiting on average per destination,
4088 * remove some random amount of goods from the station */
4089 if (rating <= 64 && waiting_avg >= 100) {
4090 int dec = Random() & 0x1F;
4091 if (waiting_avg < 200) dec &= 7;
4092 waiting -= (dec + 1) * num_dests;
4093 waiting_changed = true;
4094 }
4095
4096 /* if rating is <= 127 and there are any items waiting, maybe remove some goods. */
4097 if (rating <= 127 && waiting != 0) {
4098 uint32_t r = Random();
4099 if (rating <= (int)GB(r, 0, 7)) {
4100 /* Need to have int, otherwise it will just overflow etc. */
4101 waiting = std::max((int)waiting - (int)((GB(r, 8, 2) + 1) * num_dests), 0);
4102 waiting_changed = true;
4103 }
4104 }
4105
4106 /* At some point we really must cap the cargo. Previously this
4107 * was a strict 4095, but now we'll have a less strict, but
4108 * increasingly aggressive truncation of the amount of cargo. */
4109 static const uint WAITING_CARGO_THRESHOLD = 1 << 12;
4110 static const uint WAITING_CARGO_CUT_FACTOR = 1 << 6;
4111 static const uint MAX_WAITING_CARGO = 1 << 15;
4112
4113 if (waiting > WAITING_CARGO_THRESHOLD) {
4114 uint difference = waiting - WAITING_CARGO_THRESHOLD;
4115 waiting -= (difference / WAITING_CARGO_CUT_FACTOR);
4116
4117 waiting = std::min(waiting, MAX_WAITING_CARGO);
4118 waiting_changed = true;
4119 }
4120
4121 /* We can't truncate cargo that's already reserved for loading.
4122 * Thus StoredCount() here. */
4123 if (waiting_changed && waiting < ge->AvailableCount()) {
4124 /* Feed back the exact own waiting cargo at this station for the
4125 * next rating calculation. */
4126 ge->max_waiting_cargo = 0;
4127
4128 TruncateCargo(cs, ge, ge->AvailableCount() - waiting);
4129 } else {
4130 /* If the average number per next hop is low, be more forgiving. */
4131 ge->max_waiting_cargo = waiting_avg;
4132 }
4133 }
4134 }
4135
4136 StationID index = st->index;
4137 if (waiting_changed) {
4138 SetWindowDirty(WindowClass::StationView, index); // update whole window
4139 } else {
4140 SetWindowWidgetDirty(WindowClass::StationView, index, WID_SV_ACCEPT_RATING_LIST); // update only ratings list
4141 }
4142}
4143
4152void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
4153{
4154 GoodsEntry &ge = st->goods[cargo];
4155
4156 /* Reroute cargo in station. */
4157 if (ge.HasData()) ge.GetData().cargo.Reroute(UINT_MAX, &ge.GetData().cargo, avoid, avoid2, &ge);
4158
4159 /* Reroute cargo staged to be transferred. */
4160 for (Vehicle *v : st->loading_vehicles) {
4161 for (Vehicle *u = v; u != nullptr; u = u->Next()) {
4162 if (u->cargo_type != cargo) continue;
4163 u->cargo.Reroute(UINT_MAX, &u->cargo, avoid, avoid2, &ge);
4164 }
4165 }
4166}
4167
4177{
4178 for (CargoType cargo{}; cargo < NUM_CARGO; ++cargo) {
4179 const bool auto_distributed = (_settings_game.linkgraph.GetDistributionType(cargo) != DistributionType::Manual);
4180 GoodsEntry &ge = from->goods[cargo];
4182 if (lg == nullptr) continue;
4183 std::vector<NodeID> to_remove{};
4184 for (Edge &edge : (*lg)[ge.node].edges) {
4185 Station *to = Station::Get((*lg)[edge.dest_node].station);
4186 assert(to->goods[cargo].node == edge.dest_node);
4187 assert(TimerGameEconomy::date >= edge.LastUpdate());
4189 if (TimerGameEconomy::date - edge.LastUpdate() > timeout) {
4190 bool updated = false;
4191
4192 if (auto_distributed) {
4193 /* Have all vehicles refresh their next hops before deciding to
4194 * remove the node. */
4195 std::vector<Vehicle *> vehicles;
4196 for (const OrderList *l : OrderList::Iterate()) {
4197 bool found_from = false;
4198 bool found_to = false;
4199 for (const Order &order : l->GetOrders()) {
4200 if (!order.IsType(OT_GOTO_STATION) && !order.IsType(OT_IMPLICIT)) continue;
4201 if (order.GetDestination() == from->index) {
4202 found_from = true;
4203 if (found_to) break;
4204 } else if (order.GetDestination() == to->index) {
4205 found_to = true;
4206 if (found_from) break;
4207 }
4208 }
4209 if (!found_to || !found_from) continue;
4210 vehicles.push_back(l->GetFirstSharedVehicle());
4211 }
4212
4213 auto iter = vehicles.begin();
4214 while (iter != vehicles.end()) {
4215 Vehicle *v = *iter;
4216 /* Do not refresh links of vehicles that have been stopped in depot for a long time. */
4218 LinkRefresher::Run(v, false); // Don't allow merging. Otherwise lg might get deleted.
4219 }
4220 if (edge.LastUpdate() == TimerGameEconomy::date) {
4221 updated = true;
4222 break;
4223 }
4224
4225 Vehicle *next_shared = v->NextShared();
4226 if (next_shared) {
4227 *iter = next_shared;
4228 ++iter;
4229 } else {
4230 iter = vehicles.erase(iter);
4231 }
4232
4233 if (iter == vehicles.end()) iter = vehicles.begin();
4234 }
4235 }
4236
4237 if (!updated) {
4238 /* If it's still considered dead remove it. */
4239 to_remove.emplace_back(to->goods[cargo].node);
4240 if (ge.HasData()) ge.GetData().flows.DeleteFlows(to->index);
4241 RerouteCargo(from, cargo, to->index, from->index);
4242 }
4243 } else if (edge.last_unrestricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_unrestricted_update > timeout) {
4244 edge.Restrict();
4245 if (ge.HasData()) ge.GetData().flows.RestrictFlows(to->index);
4246 RerouteCargo(from, cargo, to->index, from->index);
4247 } else if (edge.last_restricted_update != EconomyTime::INVALID_DATE && TimerGameEconomy::date - edge.last_restricted_update > timeout) {
4248 edge.Release();
4249 }
4250 }
4251 /* Remove dead edges. */
4252 for (NodeID r : to_remove) (*lg)[ge.node].RemoveEdge(r);
4253
4254 assert(TimerGameEconomy::date >= lg->LastCompression());
4256 lg->Compress();
4257 }
4258 }
4259}
4260
4271void IncreaseStats(Station *st, CargoType cargo, StationID next_station_id, uint capacity, uint usage, uint32_t time, EdgeUpdateModes modes)
4272{
4273 GoodsEntry &ge1 = st->goods[cargo];
4274 Station *st2 = Station::Get(next_station_id);
4275 GoodsEntry &ge2 = st2->goods[cargo];
4276 LinkGraph *lg = nullptr;
4277 if (ge1.link_graph == LinkGraphID::Invalid()) {
4278 if (ge2.link_graph == LinkGraphID::Invalid()) {
4280 lg = LinkGraph::Create(cargo);
4282 ge2.link_graph = lg->index;
4283 ge2.node = lg->AddNode(st2);
4284 } else {
4285 Debug(misc, 0, "Can't allocate link graph");
4286 }
4287 } else {
4288 lg = LinkGraph::Get(ge2.link_graph);
4289 }
4290 if (lg) {
4291 ge1.link_graph = lg->index;
4292 ge1.node = lg->AddNode(st);
4293 }
4294 } else if (ge2.link_graph == LinkGraphID::Invalid()) {
4295 lg = LinkGraph::Get(ge1.link_graph);
4296 ge2.link_graph = lg->index;
4297 ge2.node = lg->AddNode(st2);
4298 } else {
4299 lg = LinkGraph::Get(ge1.link_graph);
4300 if (ge1.link_graph != ge2.link_graph) {
4302 if (lg->Size() < lg2->Size()) {
4303 LinkGraphSchedule::instance.Dequeue(lg);
4304 lg2->Merge(lg); // Updates GoodsEntries of lg
4305 lg = lg2;
4306 } else {
4307 LinkGraphSchedule::instance.Dequeue(lg2);
4308 lg->Merge(lg2); // Updates GoodsEntries of lg2
4309 }
4310 }
4311 }
4312 if (lg != nullptr) {
4313 (*lg)[ge1.node].UpdateEdge(ge2.node, capacity, usage, time, modes);
4314 }
4315}
4316
4324void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id, uint32_t time)
4325{
4326 for (const Vehicle *v = front; v != nullptr; v = v->Next()) {
4327 if (v->refit_cap > 0) {
4328 /* The cargo count can indeed be higher than the refit_cap if
4329 * wagons have been auto-replaced and subsequently auto-
4330 * refitted to a higher capacity. The cargo gets redistributed
4331 * among the wagons in that case.
4332 * As usage is not such an important figure anyway we just
4333 * ignore the additional cargo then.*/
4334 IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
4335 std::min<uint>(v->refit_cap, v->cargo.StoredCount()), time, EdgeUpdateMode::Increase);
4336 }
4337 }
4338}
4339
4340/* called for every station each tick */
4341static void StationHandleSmallTick(BaseStation *st)
4342{
4343 if (st->facilities.Test(StationFacility::Waypoint) || !st->IsInUse()) return;
4344
4345 uint8_t b = st->delete_ctr + 1;
4346 if (b >= Ticks::STATION_RATING_TICKS) b = 0;
4347 st->delete_ctr = b;
4348
4349 if (b == 0) UpdateStationRating(Station::From(st));
4350}
4351
4352void OnTick_Station()
4353{
4354 if (_game_mode == GameMode::Editor) return;
4355
4356 for (BaseStation *st : BaseStation::Iterate()) {
4357 StationHandleSmallTick(st);
4358
4359 /* Clean up the link graph about once a week. */
4362 };
4363
4364 /* Spread out big-tick over STATION_ACCEPTANCE_TICKS ticks. */
4366 /* Stop processing this station if it was deleted */
4367 if (!StationHandleBigTick(st)) continue;
4368 }
4369
4370 /* Spread out station animation over STATION_ACCEPTANCE_TICKS ticks. */
4372 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4373 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::AcceptanceTick);
4374 if (Station::IsExpected(st)) TriggerAirportAnimation(Station::From(st), AirportAnimationTrigger::AcceptanceTick);
4375 }
4376 }
4377}
4378
4380static const IntervalTimer<TimerGameEconomy> _economy_stations_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::Station}, [](auto)
4381{
4382 for (Station *st : Station::Iterate()) {
4383 for (GoodsEntry &ge : st->goods) {
4386 }
4387 }
4388});
4389
4398void ModifyStationRatingAround(TileIndex tile, Owner owner, int amount, uint radius)
4399{
4400 ForAllStationsRadius(tile, radius, [&](Station *st) {
4401 if (st->owner == owner && DistanceManhattan(tile, st->xy) <= radius) {
4402 for (GoodsEntry &ge : st->goods) {
4403 if (ge.status.Any()) {
4404 ge.rating = ClampTo<uint8_t>(ge.rating + amount);
4405 }
4406 }
4407 }
4408 });
4409}
4410
4411static uint UpdateStationWaiting(Station *st, CargoType cargo, uint amount, Source source)
4412{
4413 /* We can't allocate a CargoPacket? Then don't do anything
4414 * at all; i.e. just discard the incoming cargo. */
4415 if (!CargoPacket::CanAllocateItem()) return 0;
4416
4417 GoodsEntry &ge = st->goods[cargo];
4418 amount += ge.amount_fract;
4419 ge.amount_fract = GB(amount, 0, 8);
4420
4421 amount >>= 8;
4422 /* No new "real" cargo item yet. */
4423 if (amount == 0) return 0;
4424
4425 StationID next = ge.GetVia(st->index);
4426 ge.GetOrCreateData().cargo.Append(CargoPacket::Create(st->index, amount, source), next);
4427 LinkGraph *lg = nullptr;
4428 if (ge.link_graph == LinkGraphID::Invalid()) {
4429 if (LinkGraph::CanAllocateItem()) {
4430 lg = LinkGraph::Create(cargo);
4432 ge.link_graph = lg->index;
4433 ge.node = lg->AddNode(st);
4434 } else {
4435 Debug(misc, 0, "Can't allocate link graph");
4436 }
4437 } else {
4438 lg = LinkGraph::Get(ge.link_graph);
4439 }
4440 if (lg != nullptr) (*lg)[ge.node].UpdateSupply(amount);
4441
4442 if (!ge.HasRating()) {
4443 InvalidateWindowData(WindowClass::StationList, st->owner);
4445 }
4446
4448 TriggerStationAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4449 TriggerAirportAnimation(st, AirportAnimationTrigger::NewCargo, cargo);
4451 TriggerRoadStopAnimation(st, st->xy, StationAnimationTrigger::NewCargo, cargo);
4452
4453
4454 SetWindowDirty(WindowClass::StationView, st->index);
4455 st->MarkTilesDirty(true);
4456 return amount;
4457}
4458
4459static bool IsUniqueStationName(const std::string &name)
4460{
4461 for (const Station *st : Station::Iterate()) {
4462 if (!st->name.empty() && st->name == name) return false;
4463 }
4464
4465 return true;
4466}
4467
4475CommandCost CmdRenameStation(DoCommandFlags flags, StationID station_id, const std::string &text)
4476{
4477 Station *st = Station::GetIfValid(station_id);
4478 if (st == nullptr) return CMD_ERROR;
4479
4480 CommandCost ret = CheckOwnership(st->owner);
4481 if (ret.Failed()) return ret;
4482
4483 bool reset = text.empty();
4484
4485 if (!reset) {
4487 if (!IsUniqueStationName(text)) return CommandCost(STR_ERROR_NAME_MUST_BE_UNIQUE);
4488 }
4489
4490 if (flags.Test(DoCommandFlag::Execute)) {
4491 st->cached_name.clear();
4492 if (reset) {
4493 st->name.clear();
4494 } else {
4495 st->name = text;
4496 }
4497
4498 st->UpdateVirtCoord();
4499 InvalidateWindowData(WindowClass::StationList, st->owner, 1);
4500 }
4501
4502 return CommandCost();
4503}
4504
4512std::tuple<CommandCost, StationID> CmdMoveStationName(DoCommandFlags flags, StationID station_id, TileIndex tile)
4513{
4514 Station *st = Station::GetIfValid(station_id);
4515 if (st == nullptr) return { CMD_ERROR, StationID::Invalid() };
4516
4517 if (st->owner != OWNER_NONE) {
4518 CommandCost ret = CheckOwnership(st->owner);
4519 if (ret.Failed()) return { ret, StationID::Invalid() };
4520 }
4521
4522 const StationRect *r = &st->rect;
4523 if (!r->PtInExtendedRect(TileX(tile), TileY(tile))) {
4524 return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4525 }
4526
4527 bool other_station = false;
4528 /* Check if the tile is the base tile of another station */
4529 ForAllStationsRadius(tile, 0, [&](BaseStation *s) {
4530 if (s != nullptr) {
4531 if (s != st && s->xy == tile) other_station = true;
4532 }
4533 });
4534 if (other_station) return { CommandCost(STR_ERROR_SITE_UNSUITABLE), StationID::Invalid() };
4535
4536 if (flags.Test(DoCommandFlag::Execute)) {
4537 st->MoveSign(tile);
4538
4539 st->UpdateVirtCoord();
4540 }
4541 return { CommandCost(), station_id };
4542}
4543
4549void CcMoveStationName(Commands, const CommandCost &result, StationID station_id)
4550 {
4551 if (result.Failed()) return;
4552
4554 Station *st = Station::Get(station_id);
4555 SetViewportStationRect(st, false);
4556 }
4557
4558static void AddNearbyStationsByCatchment(TileIndex tile, StationList &stations, StationList &nearby)
4559{
4560 for (Station *st : nearby) {
4561 if (st->TileIsInCatchment(tile)) stations.insert(st);
4562 }
4563}
4564
4570{
4571 if (this->tile != INVALID_TILE) {
4572 if (IsTileType(this->tile, TileType::House)) {
4573 /* Town nearby stations need to be filtered per tile. */
4574 assert(this->w == 1 && this->h == 1);
4575 AddNearbyStationsByCatchment(this->tile, this->stations, Town::GetByTile(this->tile)->stations_near);
4576 } else {
4577 ForAllStationsAroundTiles(*this, [this](Station *st, TileIndex) {
4578 this->stations.insert(st);
4579 return true;
4580 });
4581 }
4582 this->tile = INVALID_TILE;
4583 }
4584 return this->stations;
4585}
4586
4587
4588static bool CanMoveGoodsToStation(const Station *st, CargoType cargo)
4589{
4590 /* Is the station reserved exclusively for somebody else? */
4591 if (st->owner != OWNER_NONE && st->town->exclusive_counter > 0 && st->town->exclusivity != st->owner) return false;
4592
4593 /* Lowest possible rating, better not to give cargo anymore. */
4594 if (st->goods[cargo].rating == 0) return false;
4595
4596 /* Selectively servicing stations, and not this one. */
4597 if (_settings_game.order.selectgoods && !st->goods[cargo].HasVehicleEverTriedLoading()) return false;
4598
4600 /* Passengers are never served by just a truck stop. */
4601 if (st->facilities == StationFacility::TruckStop) return false;
4602 } else {
4603 /* Non-passengers are never served by just a bus stop. */
4604 if (st->facilities == StationFacility::BusStop) return false;
4605 }
4606 return true;
4607}
4608
4609uint MoveGoodsToStation(CargoType cargo, uint amount, Source source, const StationList &all_stations, Owner exclusivity)
4610{
4611 /* Return if nothing to do. Also the rounding below fails for 0. */
4612 if (all_stations.empty()) return 0;
4613 if (amount == 0) return 0;
4614
4615 Station *first_station = nullptr;
4616 typedef std::pair<Station *, uint> StationInfo;
4617 std::vector<StationInfo> used_stations;
4618
4619 for (Station *st : all_stations) {
4620 if (exclusivity != INVALID_OWNER && exclusivity != st->owner) continue;
4621 if (!CanMoveGoodsToStation(st, cargo)) continue;
4622
4623 /* Avoid allocating a vector if there is only one station to significantly
4624 * improve performance in this common case. */
4625 if (first_station == nullptr) {
4626 first_station = st;
4627 continue;
4628 }
4629 if (used_stations.empty()) {
4630 used_stations.reserve(2);
4631 used_stations.emplace_back(first_station, 0);
4632 }
4633 used_stations.emplace_back(st, 0);
4634 }
4635
4636 /* no stations around at all? */
4637 if (first_station == nullptr) return 0;
4638
4639 if (used_stations.empty()) {
4640 /* only one station around */
4641 amount *= first_station->goods[cargo].rating + 1;
4642 return UpdateStationWaiting(first_station, cargo, amount, source);
4643 }
4644
4645 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_best = {}; // best rating for each company, including OWNER_NONE
4646 TypedIndexContainer<std::array<uint32_t, OWNER_END.base()>, Owner> company_sum = {}; // sum of ratings for each company
4647 uint best_rating = 0;
4648 uint best_sum = 0; // sum of best ratings for each company
4649
4650 for (auto &p : used_stations) {
4651 auto owner = p.first->owner;
4652 auto rating = p.first->goods[cargo].rating;
4653 if (rating > company_best[owner]) {
4654 best_sum += rating - company_best[owner]; // it's usually faster than iterating companies later
4655 company_best[owner] = rating;
4656 if (rating > best_rating) best_rating = rating;
4657 }
4658 company_sum[owner] += rating;
4659 }
4660
4661 /* From now we'll calculate with fractional cargo amounts.
4662 * First determine how much cargo we really have. */
4663 amount *= best_rating + 1;
4664
4665 uint moving = 0;
4666 for (auto &p : used_stations) {
4667 Owner owner = p.first->owner;
4668 /* Multiply the amount by (company best / sum of best for each company) to get cargo allocated to a company
4669 * and by (station rating / sum of ratings in a company) to get the result for a single station. */
4670 p.second = amount * company_best[owner] * p.first->goods[cargo].rating / best_sum / company_sum[owner];
4671 moving += p.second;
4672 }
4673
4674 /* If there is some cargo left due to rounding issues distribute it among the best rated stations. */
4675 if (amount > moving) {
4676 std::stable_sort(used_stations.begin(), used_stations.end(), [cargo](const StationInfo &a, const StationInfo &b) {
4677 return b.first->goods[cargo].rating < a.first->goods[cargo].rating;
4678 });
4679
4680 assert(amount - moving <= used_stations.size());
4681 for (uint i = 0; i < amount - moving; i++) {
4682 used_stations[i].second++;
4683 }
4684 }
4685
4686 uint moved = 0;
4687 for (auto &p : used_stations) {
4688 moved += UpdateStationWaiting(p.first, cargo, p.second, source);
4689 }
4690
4691 return moved;
4692}
4693
4694void UpdateStationDockingTiles(Station *st)
4695{
4696 st->docking_station.Clear();
4697
4698 /* For neutral stations, start with the industry area instead of dock area */
4699 const TileArea *area = st->industry != nullptr ? &st->industry->location : &st->ship_station;
4700
4701 if (area->tile == INVALID_TILE) return;
4702
4703 int x = TileX(area->tile);
4704 int y = TileY(area->tile);
4705
4706 /* Expand the area by a tile on each side while
4707 * making sure that we remain inside the map. */
4708 int x2 = std::min<int>(x + area->w + 1, Map::SizeX());
4709 int x1 = std::max<int>(x - 1, 0);
4710
4711 int y2 = std::min<int>(y + area->h + 1, Map::SizeY());
4712 int y1 = std::max<int>(y - 1, 0);
4713
4714 TileArea ta(TileXY(x1, y1), TileXY(x2 - 1, y2 - 1));
4715 for (TileIndex tile : ta) {
4716 if (IsValidTile(tile) && IsPossibleDockingTile(tile)) CheckForDockingTile(tile);
4717 }
4718}
4719
4720void BuildOilRig(TileIndex tile)
4721{
4722 if (!Station::CanAllocateItem()) {
4723 Debug(misc, 0, "Can't allocate station for oilrig at 0x{:X}, reverting to oilrig only", tile);
4724 return;
4725 }
4726
4727 Station *st = Station::Create(tile);
4728 _station_kdtree.Insert(st->index);
4729 st->town = ClosestTownFromTile(tile, UINT_MAX);
4730
4732
4733 assert(IsTileType(tile, TileType::Industry));
4734 /* Mark industry as associated both ways */
4735 st->industry = Industry::GetByTile(tile);
4736 st->industry->neutral_station = st;
4737 DeleteAnimatedTile(tile);
4738 MakeOilrig(tile, st->index, GetWaterClass(tile));
4739
4740 st->owner = OWNER_NONE;
4741 st->airport.type = AT_OILRIG;
4743 st->airport.Add(tile);
4744 st->ship_station.Add(tile);
4747 UpdateStationDockingTiles(st);
4748
4749 st->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
4750
4751 st->UpdateVirtCoord();
4752
4753 /* An industry tile has now been replaced with a station tile, this may change the overlap between station catchments and industry tiles.
4754 * Recalculate the station catchment for all stations currently in the industry's nearby list.
4755 * Clear the industry's station nearby list first because Station::RecomputeCatchment cannot remove nearby industries in this case. */
4757 StationList nearby = std::move(st->industry->stations_near);
4758 st->industry->stations_near.clear();
4759 for (Station *near : nearby) {
4760 near->RecomputeCatchment(true);
4761 UpdateStationAcceptance(near, true);
4762 }
4763 }
4764
4765 st->RecomputeCatchment();
4766 UpdateStationAcceptance(st, false);
4767}
4768
4769void DeleteOilRig(TileIndex tile)
4770{
4771 Station *st = Station::GetByTile(tile);
4772
4773 MakeWaterKeepingClass(tile, OWNER_NONE);
4774
4775 /* The oil rig station is not supposed to be shared with anything else */
4776 [[maybe_unused]] static constexpr StationFacilities expected_facility{StationFacility::Airport, StationFacility::Dock};
4777 assert(st->facilities == expected_facility && st->airport.type == AT_OILRIG);
4778 if (st->industry != nullptr && st->industry->neutral_station == st) {
4779 /* Don't leave dangling neutral station pointer */
4780 st->industry->neutral_station = nullptr;
4781 }
4782 delete st;
4783}
4784
4786static void ChangeTileOwner_Station(TileIndex tile, Owner old_owner, Owner new_owner)
4787{
4788 if (IsAnyRoadStopTile(tile)) {
4789 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
4790 /* Update all roadtypes, no matter if they are present */
4791 if (GetRoadOwner(tile, rtt) == old_owner) {
4792 RoadType rt = GetRoadType(tile, rtt);
4793 if (rt != INVALID_ROADTYPE) {
4794 /* A drive-through road-stop has always two road bits. No need to dirty windows here, we'll redraw the whole screen anyway. */
4795 Company::Get(old_owner)->infrastructure.road[rt] -= 2;
4796 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.road[rt] += 2;
4797 }
4798 SetRoadOwner(tile, rtt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
4799 }
4800 }
4801 }
4802
4803 if (!IsTileOwner(tile, old_owner)) return;
4804
4805 if (new_owner != INVALID_OWNER) {
4806 /* Update company infrastructure counts. Only do it here
4807 * if the new owner is valid as otherwise the clear
4808 * command will do it for us. No need to dirty windows
4809 * here, we'll redraw the whole screen anyway.*/
4810 Company *old_company = Company::Get(old_owner);
4811 Company *new_company = Company::Get(new_owner);
4812
4813 /* Update counts for underlying infrastructure. */
4814 switch (GetStationType(tile)) {
4815 case StationType::Rail:
4817 if (!IsStationTileBlocked(tile)) {
4818 old_company->infrastructure.rail[GetRailType(tile)]--;
4819 new_company->infrastructure.rail[GetRailType(tile)]++;
4820 }
4821 break;
4822
4823 case StationType::Bus:
4824 case StationType::Truck:
4826 /* Road stops were already handled above. */
4827 break;
4828
4829 case StationType::Buoy:
4830 case StationType::Dock:
4831 if (GetWaterClass(tile) == WaterClass::Canal) {
4832 old_company->infrastructure.water--;
4833 new_company->infrastructure.water++;
4834 }
4835 break;
4836
4837 default:
4838 break;
4839 }
4840
4841 /* Update station tile count. */
4842 if (!IsBuoy(tile) && !IsAirport(tile)) {
4843 old_company->infrastructure.station--;
4844 new_company->infrastructure.station++;
4845 }
4846
4847 /* for buoys, owner of tile is owner of water, st->owner == OWNER_NONE */
4848 SetTileOwner(tile, new_owner);
4849 InvalidateWindowClassesData(WindowClass::StationList, 0);
4850 } else {
4851 if (IsDriveThroughStopTile(tile)) {
4852 /* Remove the drive-through road stop */
4853 if (IsRoadWaypoint(tile)) {
4854 Command<Commands::RemoveFromRoadWaypoint>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, tile);
4855 } else {
4856 Command<Commands::RemoveRoadStop>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile, 1, 1, (GetStationType(tile) == StationType::Truck) ? RoadStopType::Truck : RoadStopType::Bus, false);
4857 }
4858 assert(IsTileType(tile, TileType::Road));
4859 /* Change owner of tile and all roadtypes */
4860 ChangeTileOwner(tile, old_owner, new_owner);
4861 } else {
4862 Command<Commands::LandscapeClear>::Do({DoCommandFlag::Execute, DoCommandFlag::Bankrupt}, tile);
4863 /* Set tile owner of water under (now removed) buoy and dock to OWNER_NONE.
4864 * Update owner of buoy if it was not removed (was in orders).
4865 * Do not update when owned by OWNER_WATER (sea and rivers). */
4866 if ((IsTileType(tile, TileType::Water) || IsBuoyTile(tile)) && IsTileOwner(tile, old_owner)) SetTileOwner(tile, OWNER_NONE);
4867 }
4868 }
4869}
4870
4879static CommandCost CanRemoveRoadWithStop(TileIndex tile, DoCommandFlags flags)
4880{
4881 /* Water flooding can always clear road stops. */
4882 if (_current_company == OWNER_WATER) return CommandCost();
4883
4884 CommandCost ret;
4885
4886 if (GetRoadTypeTram(tile) != INVALID_ROADTYPE) {
4887 Owner tram_owner = GetRoadOwner(tile, RoadTramType::Tram);
4888 if (tram_owner != OWNER_NONE) {
4889 ret = CheckOwnership(tram_owner);
4890 if (ret.Failed()) return ret;
4891 }
4892 }
4893
4894 if (GetRoadTypeRoad(tile) != INVALID_ROADTYPE) {
4895 Owner road_owner = GetRoadOwner(tile, RoadTramType::Road);
4896 if (road_owner == OWNER_TOWN) {
4898 if (ret.Failed()) return ret;
4899 } else if (road_owner != OWNER_NONE) {
4900 ret = CheckOwnership(road_owner);
4901 if (ret.Failed()) return ret;
4902 }
4903 }
4904
4905 return CommandCost();
4906}
4907
4909CommandCost ClearTile_Station(TileIndex tile, DoCommandFlags flags)
4910{
4911 if (flags.Test(DoCommandFlag::Auto)) {
4912 switch (GetStationType(tile)) {
4913 default: break;
4914 case StationType::Rail: return CommandCost(STR_ERROR_MUST_DEMOLISH_RAILROAD);
4915 case StationType::RailWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4916 case StationType::Airport: return CommandCost(STR_ERROR_MUST_DEMOLISH_AIRPORT_FIRST);
4917 case StationType::Truck: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_CARGO_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_TRUCK_STATION_FIRST);
4918 case StationType::Bus: return CommandCost(HasTileRoadType(tile, RoadTramType::Tram) ? STR_ERROR_MUST_DEMOLISH_PASSENGER_TRAM_STATION_FIRST : STR_ERROR_MUST_DEMOLISH_BUS_STATION_FIRST);
4919 case StationType::RoadWaypoint: return CommandCost(STR_ERROR_BUILDING_MUST_BE_DEMOLISHED);
4920 case StationType::Buoy: return CommandCost(STR_ERROR_BUOY_IN_THE_WAY);
4921 case StationType::Dock: return CommandCost(STR_ERROR_MUST_DEMOLISH_DOCK_FIRST);
4923 return CommandCostWithParam(STR_ERROR_GENERIC_OBJECT_IN_THE_WAY, STR_INDUSTRY_NAME_OIL_RIG);
4924 }
4925 }
4926
4927 switch (GetStationType(tile)) {
4928 case StationType::Rail: return RemoveRailStation(tile, flags);
4929 case StationType::RailWaypoint: return RemoveRailWaypoint(tile, flags);
4930 case StationType::Airport: return RemoveAirport(tile, flags);
4931 case StationType::Truck: [[fallthrough]];
4932 case StationType::Bus:
4933 if (IsDriveThroughStopTile(tile)) {
4934 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4935 if (remove_road.Failed()) return remove_road;
4936 }
4937 return RemoveRoadStop(tile, flags);
4939 CommandCost remove_road = CanRemoveRoadWithStop(tile, flags);
4940 if (remove_road.Failed()) return remove_road;
4941 return RemoveRoadWaypointStop(tile, flags);
4942 }
4943 case StationType::Buoy: return RemoveBuoy(tile, flags);
4944 case StationType::Dock: return RemoveDock(tile, flags);
4945 default: break;
4946 }
4947
4948 return CMD_ERROR;
4949}
4950
4952static CommandCost TerraformTile_Station(TileIndex tile, DoCommandFlags flags, int z_new, Slope tileh_new)
4953{
4954 if (_settings_game.construction.build_on_slopes && AutoslopeEnabled()) {
4955 /* TODO: If you implement newgrf callback 149 'land slope check', you have to decide what to do with it here.
4956 * TTDP does not call it.
4957 */
4958 if (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new)) {
4959 switch (GetStationType(tile)) {
4961 case StationType::Rail: {
4962 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetRailStationAxis(tile))) break;
4964 }
4965
4968
4969 case StationType::Truck:
4970 case StationType::Bus:
4972 if (IsDriveThroughStopTile(tile)) {
4973 if (!AutoslopeCheckForAxis(tile, z_new, tileh_new, GetDriveThroughStopAxis(tile))) break;
4974 } else {
4975 if (!AutoslopeCheckForEntranceEdge(tile, z_new, tileh_new, GetBayRoadStopDir(tile))) break;
4976 }
4978 }
4979
4980 default: break;
4981 }
4982 }
4983 }
4984 return Command<Commands::LandscapeClear>::Do(flags, tile);
4985}
4986
4992uint FlowStat::GetShare(StationID st) const
4993{
4994 uint32_t prev = 0;
4995 for (const auto &it : this->shares) {
4996 if (it.second == st) {
4997 return it.first - prev;
4998 } else {
4999 prev = it.first;
5000 }
5001 }
5002 return 0;
5003}
5004
5011StationID FlowStat::GetVia(StationID excluded, StationID excluded2) const
5012{
5013 if (this->unrestricted == 0) return StationID::Invalid();
5014 assert(!this->shares.empty());
5015 SharesMap::const_iterator it = this->shares.upper_bound(RandomRange(this->unrestricted));
5016 assert(it != this->shares.end() && it->first <= this->unrestricted);
5017 if (it->second != excluded && it->second != excluded2) return it->second;
5018
5019 /* We've hit one of the excluded stations.
5020 * Draw another share, from outside its range. */
5021
5022 uint end = it->first;
5023 uint begin = (it == this->shares.begin() ? 0 : (--it)->first);
5024 uint interval = end - begin;
5025 if (interval >= this->unrestricted) return StationID::Invalid(); // Only one station in the map.
5026 uint new_max = this->unrestricted - interval;
5027 uint rand = RandomRange(new_max);
5028 SharesMap::const_iterator it2 = (rand < begin) ? this->shares.upper_bound(rand) :
5029 this->shares.upper_bound(rand + interval);
5030 assert(it2 != this->shares.end() && it2->first <= this->unrestricted);
5031 if (it2->second != excluded && it2->second != excluded2) return it2->second;
5032
5033 /* We've hit the second excluded station.
5034 * Same as before, only a bit more complicated. */
5035
5036 uint end2 = it2->first;
5037 uint begin2 = (it2 == this->shares.begin() ? 0 : (--it2)->first);
5038 uint interval2 = end2 - begin2;
5039 if (interval2 >= new_max) return StationID::Invalid(); // Only the two excluded stations in the map.
5040 new_max -= interval2;
5041 if (begin > begin2) {
5042 std::swap(begin, begin2);
5043 std::swap(end, end2);
5044 std::swap(interval, interval2);
5045 }
5046 rand = RandomRange(new_max);
5047 SharesMap::const_iterator it3 = this->shares.upper_bound(this->unrestricted);
5048 if (rand < begin) {
5049 it3 = this->shares.upper_bound(rand);
5050 } else if (rand < begin2 - interval) {
5051 it3 = this->shares.upper_bound(rand + interval);
5052 } else {
5053 it3 = this->shares.upper_bound(rand + interval + interval2);
5054 }
5055 assert(it3 != this->shares.end() && it3->first <= this->unrestricted);
5056 return it3->second;
5057}
5058
5065{
5066 assert(!this->shares.empty());
5067 SharesMap new_shares;
5068 uint i = 0;
5069 for (const auto &it : this->shares) {
5070 new_shares[++i] = it.second;
5071 if (it.first == this->unrestricted) this->unrestricted = i;
5072 }
5073 this->shares.swap(new_shares);
5074 assert(!this->shares.empty() && this->unrestricted <= (--this->shares.end())->first);
5075}
5076
5083void FlowStat::ChangeShare(StationID st, int flow)
5084{
5085 /* We assert only before changing as afterwards the shares can actually
5086 * be empty. In that case the whole flow stat must be deleted then. */
5087 assert(!this->shares.empty());
5088
5089 uint removed_shares = 0;
5090 uint added_shares = 0;
5091 uint last_share = 0;
5092 SharesMap new_shares;
5093 for (const auto &it : this->shares) {
5094 if (it.second == st) {
5095 if (flow < 0) {
5096 uint share = it.first - last_share;
5097 if (flow == INT_MIN || (uint)(-flow) >= share) {
5098 removed_shares += share;
5099 if (it.first <= this->unrestricted) this->unrestricted -= share;
5100 if (flow != INT_MIN) flow += share;
5101 last_share = it.first;
5102 continue; // remove the whole share
5103 }
5104 removed_shares += (uint)(-flow);
5105 } else {
5106 added_shares += (uint)(flow);
5107 }
5108 if (it.first <= this->unrestricted) this->unrestricted += flow;
5109
5110 /* If we don't continue above the whole flow has been added or
5111 * removed. */
5112 flow = 0;
5113 }
5114 new_shares[it.first + added_shares - removed_shares] = it.second;
5115 last_share = it.first;
5116 }
5117 if (flow > 0) {
5118 new_shares[last_share + (uint)flow] = st;
5119 if (this->unrestricted < last_share) {
5120 this->ReleaseShare(st);
5121 } else {
5122 this->unrestricted += flow;
5123 }
5124 }
5125 this->shares.swap(new_shares);
5126}
5127
5133void FlowStat::RestrictShare(StationID st)
5134{
5135 assert(!this->shares.empty());
5136 uint flow = 0;
5137 uint last_share = 0;
5138 SharesMap new_shares;
5139 for (auto &it : this->shares) {
5140 if (flow == 0) {
5141 if (it.first > this->unrestricted) return; // Not present or already restricted.
5142 if (it.second == st) {
5143 flow = it.first - last_share;
5144 this->unrestricted -= flow;
5145 } else {
5146 new_shares[it.first] = it.second;
5147 }
5148 } else {
5149 new_shares[it.first - flow] = it.second;
5150 }
5151 last_share = it.first;
5152 }
5153 if (flow == 0) return;
5154 new_shares[last_share + flow] = st;
5155 this->shares.swap(new_shares);
5156 assert(!this->shares.empty());
5157}
5158
5164void FlowStat::ReleaseShare(StationID st)
5165{
5166 assert(!this->shares.empty());
5167 uint flow = 0;
5168 uint next_share = 0;
5169 bool found = false;
5170 for (SharesMap::reverse_iterator it(this->shares.rbegin()); it != this->shares.rend(); ++it) {
5171 if (it->first < this->unrestricted) return; // Note: not <= as the share may hit the limit.
5172 if (found) {
5173 flow = next_share - it->first;
5174 this->unrestricted += flow;
5175 break;
5176 } else {
5177 if (it->first == this->unrestricted) return; // !found -> Limit not hit.
5178 if (it->second == st) found = true;
5179 }
5180 next_share = it->first;
5181 }
5182 if (flow == 0) return;
5183 SharesMap new_shares;
5184 new_shares[flow] = st;
5185 for (SharesMap::iterator it(this->shares.begin()); it != this->shares.end(); ++it) {
5186 if (it->second != st) {
5187 new_shares[flow + it->first] = it->second;
5188 } else {
5189 flow = 0;
5190 }
5191 }
5192 this->shares.swap(new_shares);
5193 assert(!this->shares.empty());
5194}
5195
5202{
5203 assert(runtime > 0);
5204 SharesMap new_shares;
5205 uint share = 0;
5206 for (auto i : this->shares) {
5207 share = std::max(share + 1, i.first * 30 / runtime);
5208 new_shares[share] = i.second;
5209 if (this->unrestricted == i.first) this->unrestricted = share;
5210 }
5211 this->shares.swap(new_shares);
5212}
5213
5220void FlowStatMap::AddFlow(StationID origin, StationID via, uint flow)
5221{
5222 FlowStatMap::iterator origin_it = this->find(origin);
5223 if (origin_it == this->end()) {
5224 this->emplace(origin, FlowStat(via, flow));
5225 } else {
5226 origin_it->second.ChangeShare(via, flow);
5227 assert(!origin_it->second.GetShares()->empty());
5228 }
5229}
5230
5239void FlowStatMap::PassOnFlow(StationID origin, StationID via, uint flow)
5240{
5241 FlowStatMap::iterator prev_it = this->find(origin);
5242 if (prev_it == this->end()) {
5243 FlowStat fs(via, flow);
5244 fs.AppendShare(StationID::Invalid(), flow);
5245 this->emplace(origin, fs);
5246 } else {
5247 prev_it->second.ChangeShare(via, flow);
5248 prev_it->second.ChangeShare(StationID::Invalid(), flow);
5249 assert(!prev_it->second.GetShares()->empty());
5250 }
5251}
5252
5258{
5259 for (auto &i : *this) {
5260 FlowStat &fs = i.second;
5261 uint local = fs.GetShare(StationID::Invalid());
5262 if (local > INT_MAX) { // make sure it fits in an int
5263 fs.ChangeShare(self, -INT_MAX);
5264 fs.ChangeShare(StationID::Invalid(), -INT_MAX);
5265 local -= INT_MAX;
5266 }
5267 fs.ChangeShare(self, -(int)local);
5268 fs.ChangeShare(StationID::Invalid(), -(int)local);
5269
5270 /* If the local share is used up there must be a share for some
5271 * remote station. */
5272 assert(!fs.GetShares()->empty());
5273 }
5274}
5275
5282std::vector<StationID> FlowStatMap::DeleteFlows(StationID via)
5283{
5284 std::vector<StationID> ret;
5285 for (FlowStatMap::iterator f_it = this->begin(); f_it != this->end();) {
5286 FlowStat &s_flows = f_it->second;
5287 s_flows.ChangeShare(via, INT_MIN);
5288 if (s_flows.GetShares()->empty()) {
5289 ret.push_back(f_it->first);
5290 this->erase(f_it++);
5291 } else {
5292 ++f_it;
5293 }
5294 }
5295 return ret;
5296}
5297
5303{
5304 for (auto &it : *this) {
5305 it.second.RestrictShare(via);
5306 }
5307}
5308
5313void FlowStatMap::ReleaseFlows(StationID via)
5314{
5315 for (auto &it : *this) {
5316 it.second.ReleaseShare(via);
5317 }
5318}
5319
5325{
5326 uint ret = 0;
5327 for (const auto &it : *this) {
5328 ret += (--(it.second.GetShares()->end()))->first;
5329 }
5330 return ret;
5331}
5332
5338uint FlowStatMap::GetFlowVia(StationID via) const
5339{
5340 uint ret = 0;
5341 for (const auto &it : *this) {
5342 ret += it.second.GetShare(via);
5343 }
5344 return ret;
5345}
5346
5352uint FlowStatMap::GetFlowFrom(StationID from) const
5353{
5354 FlowStatMap::const_iterator i = this->find(from);
5355 if (i == this->end()) return 0;
5356 return (--(i->second.GetShares()->end()))->first;
5357}
5358
5365uint FlowStatMap::GetFlowFromVia(StationID from, StationID via) const
5366{
5367 FlowStatMap::const_iterator i = this->find(from);
5368 if (i == this->end()) return 0;
5369 return i->second.GetShare(via);
5370}
5371
5373static CommandCost CheckBuildAbove_Station(TileIndex tile, [[maybe_unused]] DoCommandFlags flags, [[maybe_unused]] Axis axis, int height)
5374{
5375 StationType type = GetStationType(tile);
5376 auto bridgeable_info = GetStationBridgeableTileInfo(type);
5377
5378 switch (type) {
5379 case StationType::Rail:
5381 if (const StationSpec *spec = GetStationSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5382 break;
5383
5384 case StationType::Bus:
5385 case StationType::Truck:
5387 if (const RoadStopSpec *spec = GetRoadStopSpec(tile); spec != nullptr) bridgeable_info = spec->bridgeable_info;
5388 break;
5389
5390 default: break;
5391 }
5392
5393 return IsStationBridgeAboveOk(tile, bridgeable_info, type, GetStationGfx(tile), height);
5394}
5395
5397extern const TileTypeProcs _tile_type_station_procs = {
5398 .draw_tile_proc = DrawTile_Station,
5399 .get_slope_pixel_z_proc = [](TileIndex tile, uint, uint, bool) { return GetTileMaxPixelZ(tile); },
5400 .clear_tile_proc = ClearTile_Station,
5401 .get_tile_desc_proc = GetTileDesc_Station,
5402 .get_tile_track_status_proc = GetTileTrackStatus_Station,
5403 .click_tile_proc = ClickTile_Station,
5404 .animate_tile_proc = AnimateTile_Station,
5405 .tile_loop_proc = TileLoop_Station,
5406 .change_tile_owner_proc = ChangeTileOwner_Station,
5407 .vehicle_enter_tile_proc = VehicleEnterTile_Station,
5408 .get_foundation_proc = [](TileIndex, Slope tileh) { return FlatteningFoundation(tileh); },
5409 .terraform_tile_proc = TerraformTile_Station,
5410 .check_build_above_proc = CheckBuildAbove_Station,
5411};
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:130
@ FLYING
Vehicle is flying in the air.
Definition airport.h:77
@ 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 T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
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.
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
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:110
static constexpr CargoType NUM_CARGO
Maximum number of cargo types in a game.
Definition cargo_type.h:75
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
@ Passengers
Passengers.
Definition cargotype.h:51
bool IsCargoInClass(CargoType cargo, CargoClasses cc)
Does cargo c have cargo class cc?
Definition cargotype.h:236
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.
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.
Iterator to iterate over all tiles belonging to a bitmaptilearea.
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?
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:37
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:240
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:234
static const uint MIN_TIMEOUT_DISTANCE
Minimum effective distance for timeout calculation.
Definition linkgraph.h:174
static constexpr TimerGameEconomy::Date STALE_LINK_DEPOT_TIMEOUT
Number of days before deleting links served only by vehicles stopped in depot.
Definition linkgraph.h:177
static constexpr TimerGameEconomy::Date COMPRESSION_INTERVAL
Minimum number of days between subsequent compressions of a LG.
Definition linkgraph.h:180
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.
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:115
SpriteID single_x
single piece of rail in X direction, without ground
Definition rail.h:125
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition rail.h:220
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:126
StringID name
Name of this rail type.
Definition rail.h:165
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition rail.h:190
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition rail.h:287
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:116
struct RoadTypeInfo::@070000167274302256150317022075324310363002361255 strings
Strings associated with the rail type.
StringID name
Name of this rail type.
Definition road.h:77
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.
Base class for tile iterators.
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.
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:416
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.
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(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
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.
@ Begin
Used for iterations.
@ 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:106
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:552
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:1037
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.
HouseZone
Concentric rings of zoning around the centre of a town.
Definition house.h:57
@ TownEdge
Edge of the town; roads without pavement.
Definition house.h:58
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:57
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.
std::tuple< Slope, int > GetFoundationPixelSlope(TileIndex tile)
Get slope of a tile on top of a (possible) foundation If a tile does not have a foundation,...
Definition landscape.h:67
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.
@ 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:229
uint DistanceMax(TileIndex t0, TileIndex t1)
Gets the biggest distance component (x or y) between the two given tiles.
Definition map.cpp:201
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:120
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:169
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.
Types related to the misc widgets.
@ RoadStops
Road stops feature.
Definition newgrf.h:94
@ Stations
Stations feature.
Definition newgrf.h:78
@ Airports
Airports feature.
Definition newgrf.h:87
@ AirportTiles
Airport tiles feature.
Definition newgrf.h:91
uint8_t StationGfx
Copy from station_map.h.
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.
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
bool Convert8bitBooleanCallback(const GRFFile *grffile, uint16_t cbid, uint16_t cb_res)
Converts a callback result into a boolean.
GRFConfig * GetGRFConfig(uint32_t 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.
@ 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:917
@ Acceptance
A type of cargo is (no longer) accepted.
Definition news_type.h:43
@ Small
Small news item. (Information window with text and viewport).
Definition news_type.h:79
@ InColour
News item is shown in colour (otherwise it is shown in black & white).
Definition news_type.h:90
@ 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:43
@ Overlay
Images for overlaying track.
Definition rail.h:42
Money RailBuildCost(RailType railtype)
Returns the cost of building the specified railtype.
Definition rail.h:429
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:377
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:301
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition rail.h:61
@ RTO_Y
Piece of rail in Y direction.
Definition rail.h:63
@ RTO_X
Piece of rail in X direction.
Definition rail.h:62
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:625
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:25
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition rail_type.h:32
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:165
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:230
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:215
@ Roadstop
Required: Bay stop surface.
Definition road.h:47
@ Ground
Required: Main group of ground images.
Definition road.h:39
@ Overlay
Optional: Images for overlaying track.
Definition road.h:38
Money RoadBuildCost(RoadType roadtype)
Returns the cost of building the specified roadtype.
Definition road.h:240
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:183
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:255
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:66
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:64
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:67
static constexpr RoadTramTypes ROADTRAMTYPES_ALL
All possible RoadTramTypes.
Definition road_type.h:48
RoadType
The different roadtypes we support.
Definition road_type.h:23
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:28
RoadTramType
The different types of road type.
Definition road_type.h:37
@ Tram
Tram type.
Definition road_type.h:39
@ Road
Road type.
Definition road_type.h:38
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:568
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition signal.cpp:596
@ Enter
signal entering the block found
Definition signal.cpp:262
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:160
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:369
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:239
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:54
@ FOUNDATION_LEVELED
The tile is leveled up to a flat slope.
Definition slope_type.h:100
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 PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1619
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1559
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1549
static constexpr uint8_t PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition sprites.h:1562
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 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.
CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta)
Check whether we can expand the rail part of the given station.
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.
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.
@ Heliport
Standalone heliport.
@ Rail
Railway station.
@ Oilrig
Heliport of an oilrig.
@ Road
Truck or bus stop.
@ Dock
Ship dock.
@ 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.
static constexpr DiagDirectionIndexArray< uint8_t > _dock_h_chk
Y dimension of dock for each direction.
CommandCost FindJoiningBaseStation(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, T **st, F filter)
Find a nearby station that joins this station.
Town * AirportGetNearestTown(const AirportSpec *as, Direction rotation, TileIndex tile, TileIterator &&it, uint &mindist)
Finds the town nearest to given airport.
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:44
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:68
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:80
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:35
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:28
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:92
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?
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:36
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:56
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.
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:351
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:336
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
Functions related to OTTD's strings.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const 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:73
@ Airplanes
Can planes land on this airport type?
Definition airport.h:162
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...
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
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.
VehicleType type
Type of vehicle.
Class for storing amounts of cargo.
Definition cargo_type.h:117
Specification of a cargo type.
Definition cargotype.h:75
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:139
CargoType Index() const
Determines index of this cargospec.
Definition cargotype.h:109
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition cargotype.h:192
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.
const struct GRFFile * grffile
grf file that introduced this entity
uint32_t grfid
grfid 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:62
IndustryType type
type of industry.
Definition industry.h:115
ProducedCargoes produced
produced cargo slots
Definition industry.h:110
Owner owner
owner of the industry. Which SHOULD always be (imho) OWNER_NONE
Definition industry.h:116
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:251
TileArea location
Location of the industry.
Definition industry.h:106
Station * neutral_station
Associated neutral station.
Definition industry.h:108
StationList stations_near
NOSAVE: List of nearby stations.
Definition industry.h:123
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:384
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:34
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:67
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...
uint16_t w
The width of the area.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition tilearea.cpp:43
void Clear()
Clears the 'tile area', i.e.
TileIndex tile
The base tile of the area.
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.
Definition tilearea.cpp:123
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 Industry * Get(auto index)
static T * Create(Targs &&... args)
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:32
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 > used_names
Used default station suffixes.
bool IsAvailable(StringID str) const
Is the given station name available, and not already used?
StationRect - used to track station spread out rectangle - cheaper than scanning whole map.
bool PtInExtendedRect(int x, int y, int distance=0) const
Determines whether a given point (x, y) is within a certain distance of the station rectangle.
Definition station.cpp:567
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.
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:469
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:39
uint16_t rail_speed
Speed limit of rail (bridges and track).
Definition tile_cmd.h:52
std::optional< std::string > grf
newGRF used for the tile contents
Definition tile_cmd.h:50
StringID station_name
Type of station within the class.
Definition tile_cmd.h:46
StringID str
Description of the tile.
Definition tile_cmd.h:40
TimerGameCalendar::Date build_date
Date of construction of tile contents.
Definition tile_cmd.h:44
std::array< Owner, 4 > owner
Name of the owner(s).
Definition tile_cmd.h:42
StringID airport_class
Name of the airport class.
Definition tile_cmd.h:47
StringID airport_name
Name of the airport.
Definition tile_cmd.h:48
uint16_t tram_speed
Speed limit of tram (bridges and track).
Definition tile_cmd.h:56
StringID roadtype
Type of road on the tile.
Definition tile_cmd.h:53
StringID tramtype
Type of tram on the tile.
Definition tile_cmd.h:55
StringID railtype
Type of rail on the tile.
Definition tile_cmd.h:51
uint16_t road_speed
Speed limit of road (bridges and track).
Definition tile_cmd.h:54
std::array< StringID, 4 > owner_type
Type of each owner.
Definition tile_cmd.h:43
StringID airport_tile_name
Name of the airport tile.
Definition tile_cmd.h:49
StringID station_class
Class of station.
Definition tile_cmd.h:45
Tile information, used while rendering the tile.
Definition tile_cmd.h:33
Slope tileh
Slope of the tile.
Definition tile_cmd.h:34
TileIndex tile
Tile index.
Definition tile_cmd.h:35
Town data structure.
Definition town.h:63
CompanyMask statues
which companies have a statue?
Definition town.h:81
TileIndex xy
town center tile
Definition town.h:64
uint16_t noise_reached
level of noise that all the airports are generating
Definition town.h:79
uint16_t MaxTownNoise() const
Calculate the max town noise.
Definition town.h:223
CompanyID exclusivity
which company has exclusivity
Definition town.h:86
uint8_t exclusive_counter
months till the exclusivity expires
Definition town.h:87
Track status of a tile.
Definition track_type.h:132
'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:256
void AddAcceptedCargo(TileIndex tile, CargoArray &acceptance, CargoTypes &always_accepted)
Obtain cargo acceptance of a tile.
Definition tile_cmd.h:244
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
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal 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,...
TrackBits TrackToTrackBits(Track track)
Maps a Track to the corresponding TrackBits value.
Definition track_func.h:77
TrackdirBits TrackBitsToTrackdirBits(TrackBits bits)
Converts TrackBits to TrackdirBits while allowing both directions.
Definition track_func.h:319
bool IsReversingRoadTrackdir(Trackdir dir)
Checks whether the trackdir means that we are reversing.
Definition track_func.h:631
Trackdir ReverseTrackdir(Trackdir trackdir)
Maps a trackdir to the reverse trackdir.
Definition track_func.h:247
TrackBits AxisToTrackBits(Axis a)
Maps an Axis to the corresponding TrackBits value.
Definition track_func.h:88
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a DiagDirection to the associated diagonal TrackBits.
Definition track_func.h:482
Track AxisToTrack(Axis a)
Convert an Axis to the corresponding Track Axis::X -> TRACK_X Axis::Y -> TRACK_Y Uses the fact that t...
Definition track_func.h:66
DiagDirection TrackdirToExitdir(Trackdir trackdir)
Maps a trackdir to the (4-way) direction the tile is exited when following that trackdir.
Definition track_func.h:394
TrackBits
Bitfield corresponding to Track.
Definition track_type.h:42
@ TRACK_BIT_UPPER
Upper track.
Definition track_type.h:46
@ TRACK_BIT_LEFT
Left track.
Definition track_type.h:48
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:45
@ TRACK_BIT_NONE
No track.
Definition track_type.h:43
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:44
@ TRACK_BIT_ALL
All possible tracks.
Definition track_type.h:57
@ TRACK_BIT_RIGHT
Right track.
Definition track_type.h:49
Trackdir
Enumeration for tracks and directions.
Definition track_type.h:73
@ TRACKDIR_BIT_NONE
No track build.
Definition track_type.h:112
Track
These are used to specify a single track.
Definition track_type.h:19
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.
@ TRANSPORT_RAIL
Transport by train.
@ TRANSPORT_ROAD
Transport by road vehicle.
@ TRANSPORT_WATER
Transport over water.
Functions that have tunnels and bridges in common.
CommandCost EnsureNoVehicleOnGround(TileIndex tile)
Ensure there is no vehicle at the ground at the given position.
Definition vehicle.cpp:557
@ 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:591
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:759
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:658
void EndSpriteCombine()
Terminates a block of sprites started by StartSpriteCombine.
Definition viewport.cpp:769
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:579
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:353
bool IsTileOnWater(Tile t)
Tests if the tile was built on water.
Definition water_map.h:138
WaterClass
classes of water (for WaterTileType::Clear water tile type).
Definition water_map.h:39
@ Invalid
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:43
@ Canal
Canal.
Definition water_map.h:41
@ Sea
Sea.
Definition water_map.h:40
bool HasTileWaterClass(Tile t)
Checks whether the tile has an waterclass associated.
Definition water_map.h:103
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:114
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition water_map.h:375
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:364
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:149
bool IsWaterTile(Tile t)
Is it a water tile with plain water?
Definition water_map.h:192
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:1209
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3230
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:3322
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:3216
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3200
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:3340
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