2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file newgrf_station.cpp Functions for dealing with station classes and custom stations. */
12 #include "station_base.h"
13 #include "waypoint_base.h"
14 #include "roadstop_base.h"
15 #include "newgrf_cargo.h"
16 #include "newgrf_station.h"
17 #include "newgrf_spritegroup.h"
18 #include "newgrf_sound.h"
19 #include "newgrf_railtype.h"
21 #include "newgrf_town.h"
22 #include "company_func.h"
23 #include "tunnelbridge_map.h"
24 #include "newgrf_animation_base.h"
25 #include "newgrf_class_func.h"
27 #include "safeguards.h"
30 template <typename Tspec
, typename Tid
, Tid Tmax
>
31 /* static */ void NewGRFClass
<Tspec
, Tid
, Tmax
>::InsertDefaults()
33 /* Set up initial data */
34 classes
[0].global_id
= 'DFLT';
35 classes
[0].name
= STR_STATION_CLASS_DFLT
;
36 classes
[0].Insert(nullptr);
38 classes
[1].global_id
= 'WAYP';
39 classes
[1].name
= STR_STATION_CLASS_WAYP
;
40 classes
[1].Insert(nullptr);
43 template <typename Tspec
, typename Tid
, Tid Tmax
>
44 bool NewGRFClass
<Tspec
, Tid
, Tmax
>::IsUIAvailable(uint index
) const
49 INSTANTIATE_NEWGRF_CLASS_METHODS(StationClass
, StationSpec
, StationClassID
, STAT_CLASS_MAX
)
51 static const uint NUM_STATIONSSPECS_PER_STATION
= 255; ///< Maximum number of parts per station.
59 struct ETileArea
: TileArea
{
60 ETileArea(const BaseStation
*st
, TileIndex tile
, TriggerArea ta
)
63 default: NOT_REACHED();
73 Axis axis
= GetRailStationAxis(tile
);
74 TileIndexDiff delta
= TileOffsByDiagDir(AxisToDiagDir(axis
));
76 for (end
= tile
; IsRailStationTile(end
+ delta
) && IsCompatibleTrainStationTile(end
+ delta
, tile
); end
+= delta
) { /* Nothing */ }
77 for (start
= tile
; IsRailStationTile(start
- delta
) && IsCompatibleTrainStationTile(start
- delta
, tile
); start
-= delta
) { /* Nothing */ }
80 this->w
= TileX(end
) - TileX(start
) + 1;
81 this->h
= TileY(end
) - TileY(start
) + 1;
86 st
->GetTileArea(this, Station::IsExpected(st
) ? STATION_RAIL
: STATION_WAYPOINT
);
94 * Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
95 * if not centered: .TNLcCpP, if centered: .TNL..CP
96 * - T = Tile layout number (#GetStationGfx)
97 * - N = Number of platforms
98 * - L = Length of platforms
99 * - C = Current platform number from start, c = from end
100 * - P = Position along platform from start, p = from end
102 * if centered, C/P start from the centre and c/p are not available.
103 * @return Platform information in bit-stuffed format.
105 uint32
GetPlatformInfo(Axis axis
, byte tile
, int platforms
, int length
, int x
, int y
, bool centred
)
109 if (axis
== AXIS_X
) {
110 Swap(platforms
, length
);
119 SB(retval
, 0, 4, y
& 0xF);
120 SB(retval
, 4, 4, x
& 0xF);
122 SB(retval
, 0, 4, std::min(15, y
));
123 SB(retval
, 4, 4, std::min(15, length
- y
- 1));
124 SB(retval
, 8, 4, std::min(15, x
));
125 SB(retval
, 12, 4, std::min(15, platforms
- x
- 1));
127 SB(retval
, 16, 4, std::min(15, length
));
128 SB(retval
, 20, 4, std::min(15, platforms
));
129 SB(retval
, 24, 4, tile
);
136 * Find the end of a railway station, from the \a tile, in the direction of \a delta.
137 * @param tile Start tile.
138 * @param delta Movement direction.
139 * @param check_type Stop when the custom station type changes.
140 * @param check_axis Stop when the station direction changes.
141 * @return Found end of the railway station.
143 static TileIndex
FindRailStationEnd(TileIndex tile
, TileIndexDiff delta
, bool check_type
, bool check_axis
)
146 Axis orig_axis
= AXIS_X
;
147 StationID sid
= GetStationIndex(tile
);
149 if (check_type
) orig_type
= GetCustomStationSpecIndex(tile
);
150 if (check_axis
) orig_axis
= GetRailStationAxis(tile
);
153 TileIndex new_tile
= TILE_ADD(tile
, delta
);
155 if (!IsTileType(new_tile
, MP_STATION
) || GetStationIndex(new_tile
) != sid
) break;
156 if (!HasStationRail(new_tile
)) break;
157 if (check_type
&& GetCustomStationSpecIndex(new_tile
) != orig_type
) break;
158 if (check_axis
&& GetRailStationAxis(new_tile
) != orig_axis
) break;
166 static uint32
GetPlatformInfoHelper(TileIndex tile
, bool check_type
, bool check_axis
, bool centred
)
168 int tx
= TileX(tile
);
169 int ty
= TileY(tile
);
170 int sx
= TileX(FindRailStationEnd(tile
, TileDiffXY(-1, 0), check_type
, check_axis
));
171 int sy
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, -1), check_type
, check_axis
));
172 int ex
= TileX(FindRailStationEnd(tile
, TileDiffXY( 1, 0), check_type
, check_axis
)) + 1;
173 int ey
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, 1), check_type
, check_axis
)) + 1;
178 return GetPlatformInfo(GetRailStationAxis(tile
), GetStationGfx(tile
), ex
, ey
, tx
, ty
, centred
);
182 static uint32
GetRailContinuationInfo(TileIndex tile
)
184 /* Tile offsets and exit dirs for X axis */
185 static const Direction x_dir
[8] = { DIR_SW
, DIR_NE
, DIR_SE
, DIR_NW
, DIR_S
, DIR_E
, DIR_W
, DIR_N
};
186 static const DiagDirection x_exits
[8] = { DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SW
, DIAGDIR_NE
};
188 /* Tile offsets and exit dirs for Y axis */
189 static const Direction y_dir
[8] = { DIR_SE
, DIR_NW
, DIR_SW
, DIR_NE
, DIR_S
, DIR_W
, DIR_E
, DIR_N
};
190 static const DiagDirection y_exits
[8] = { DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SE
, DIAGDIR_NW
};
192 Axis axis
= GetRailStationAxis(tile
);
194 /* Choose appropriate lookup table to use */
195 const Direction
*dir
= axis
== AXIS_X
? x_dir
: y_dir
;
196 const DiagDirection
*diagdir
= axis
== AXIS_X
? x_exits
: y_exits
;
201 for (i
= 0; i
< lengthof(x_dir
); i
++, dir
++, diagdir
++) {
202 TileIndex neighbour_tile
= tile
+ TileOffsByDir(*dir
);
203 TrackBits trackbits
= TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile
, TRANSPORT_RAIL
, 0));
204 if (trackbits
!= TRACK_BIT_NONE
) {
205 /* If there is any track on the tile, set the bit in the second byte */
208 /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
209 * with the next tile because the ramp is not going in the right direction. */
210 if (IsTileType(neighbour_tile
, MP_TUNNELBRIDGE
) && GetTunnelBridgeDirection(neighbour_tile
) != *diagdir
) {
214 /* If any track reaches our exit direction, set the bit in the lower byte */
215 if (trackbits
& DiagdirReachesTracks(*diagdir
)) SetBit(res
, i
);
223 /* Station Resolver Functions */
224 /* virtual */ uint32
StationScopeResolver::GetRandomBits() const
226 return (this->st
== nullptr ? 0 : this->st
->random_bits
) | (this->tile
== INVALID_TILE
? 0 : GetStationTileRandomBits(this->tile
) << 16);
230 /* virtual */ uint32
StationScopeResolver::GetTriggers() const
232 return this->st
== nullptr ? 0 : this->st
->waiting_triggers
;
237 * Station variable cache
238 * This caches 'expensive' station variable lookups which iterate over
239 * several tiles that may be called multiple times per Resolve().
248 uint8 valid
; ///< Bits indicating what variable is valid (for each bit, \c 0 is invalid, \c 1 is valid).
252 * Get the town scope associated with a station, if it exists.
253 * On the first call, the town scope is created (if possible).
254 * @return Town scope, if available.
256 TownScopeResolver
*StationResolverObject::GetTown()
258 if (this->town_scope
== nullptr) {
260 if (this->station_scope
.st
!= nullptr) {
261 t
= this->station_scope
.st
->town
;
262 } else if (this->station_scope
.tile
!= INVALID_TILE
) {
263 t
= ClosestTownFromTile(this->station_scope
.tile
, UINT_MAX
);
265 if (t
== nullptr) return nullptr;
266 this->town_scope
= new TownScopeResolver(*this, t
, this->station_scope
.st
== nullptr);
268 return this->town_scope
;
271 /* virtual */ uint32
StationScopeResolver::GetVariable(byte variable
, uint32 parameter
, bool *available
) const
273 if (this->st
== nullptr) {
274 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
280 case 0x49: return 0x2110000; // Platforms, tracks & position
281 case 0x42: return 0; // Rail type (XXX Get current type from GUI?)
282 case 0x43: return GetCompanyInfo(_current_company
); // Station owner
283 case 0x44: return 2; // PBS status
284 case 0x67: // Land info of nearby tile
285 if (this->axis
!= INVALID_AXIS
&& this->tile
!= INVALID_TILE
) {
286 TileIndex tile
= this->tile
;
287 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
, true, this->axis
); // only perform if it is required
289 Slope tileh
= GetTileSlope(tile
);
290 bool swap
= (this->axis
== AXIS_Y
&& HasBit(tileh
, CORNER_W
) != HasBit(tileh
, CORNER_E
));
292 return GetNearbyTileInformation(tile
, this->ro
.grffile
->grf_version
>= 8) ^ (swap
? SLOPE_EW
: 0);
296 case 0xFA: return Clamp(_date
- DAYS_TILL_ORIGINAL_BASE_YEAR
, 0, 65535); // Build date, clamped to a 16 bit value
304 /* Calculated station variables */
306 if (!HasBit(_svc
.valid
, 0)) { _svc
.v40
= GetPlatformInfoHelper(this->tile
, false, false, false); SetBit(_svc
.valid
, 0); }
310 if (!HasBit(_svc
.valid
, 1)) { _svc
.v41
= GetPlatformInfoHelper(this->tile
, true, false, false); SetBit(_svc
.valid
, 1); }
313 case 0x42: return GetTerrainType(this->tile
) | (GetReverseRailTypeTranslation(GetRailType(this->tile
), this->statspec
->grf_prop
.grffile
) << 8);
314 case 0x43: return GetCompanyInfo(this->st
->owner
); // Station owner
315 case 0x44: return HasStationReservation(this->tile
) ? 7 : 4; // PBS status
317 if (!HasBit(_svc
.valid
, 2)) { _svc
.v45
= GetRailContinuationInfo(this->tile
); SetBit(_svc
.valid
, 2); }
321 if (!HasBit(_svc
.valid
, 3)) { _svc
.v46
= GetPlatformInfoHelper(this->tile
, false, false, true); SetBit(_svc
.valid
, 3); }
325 if (!HasBit(_svc
.valid
, 4)) { _svc
.v47
= GetPlatformInfoHelper(this->tile
, true, false, true); SetBit(_svc
.valid
, 4); }
329 if (!HasBit(_svc
.valid
, 5)) { _svc
.v49
= GetPlatformInfoHelper(this->tile
, false, true, false); SetBit(_svc
.valid
, 5); }
332 case 0x4A: // Animation frame of tile
333 return GetAnimationFrame(this->tile
);
335 /* Variables which use the parameter */
336 /* Variables 0x60 to 0x65 and 0x69 are handled separately below */
337 case 0x66: { // Animation frame of nearby tile
338 TileIndex tile
= this->tile
;
339 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
);
340 return this->st
->TileBelongsToRailStation(tile
) ? GetAnimationFrame(tile
) : UINT_MAX
;
343 case 0x67: { // Land info of nearby tile
344 Axis axis
= GetRailStationAxis(this->tile
);
345 TileIndex tile
= this->tile
;
346 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
); // only perform if it is required
348 Slope tileh
= GetTileSlope(tile
);
349 bool swap
= (axis
== AXIS_Y
&& HasBit(tileh
, CORNER_W
) != HasBit(tileh
, CORNER_E
));
351 return GetNearbyTileInformation(tile
, this->ro
.grffile
->grf_version
>= 8) ^ (swap
? SLOPE_EW
: 0);
354 case 0x68: { // Station info of nearby tiles
355 TileIndex nearby_tile
= GetNearbyTile(parameter
, this->tile
);
357 if (!HasStationTileRail(nearby_tile
)) return 0xFFFFFFFF;
359 uint32 grfid
= this->st
->speclist
[GetCustomStationSpecIndex(this->tile
)].grfid
;
360 bool perpendicular
= GetRailStationAxis(this->tile
) != GetRailStationAxis(nearby_tile
);
361 bool same_station
= this->st
->TileBelongsToRailStation(nearby_tile
);
362 uint32 res
= GB(GetStationGfx(nearby_tile
), 1, 2) << 12 | !!perpendicular
<< 11 | !!same_station
<< 10;
364 if (IsCustomStationSpecIndex(nearby_tile
)) {
365 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[GetCustomStationSpecIndex(nearby_tile
)];
366 res
|= 1 << (ssl
.grfid
!= grfid
? 9 : 8) | ssl
.localidx
;
371 case 0x6A: { // GRFID of nearby station tiles
372 TileIndex nearby_tile
= GetNearbyTile(parameter
, this->tile
);
374 if (!HasStationTileRail(nearby_tile
)) return 0xFFFFFFFF;
375 if (!IsCustomStationSpecIndex(nearby_tile
)) return 0;
377 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[GetCustomStationSpecIndex(nearby_tile
)];
381 /* General station variables */
382 case 0x82: return 50;
383 case 0x84: return this->st
->string_id
;
385 case 0xF0: return this->st
->facilities
;
386 case 0xFA: return Clamp(this->st
->build_date
- DAYS_TILL_ORIGINAL_BASE_YEAR
, 0, 65535);
389 return this->st
->GetNewGRFVariable(this->ro
, variable
, parameter
, available
);
392 uint32
Station::GetNewGRFVariable(const ResolverObject
&object
, byte variable
, byte parameter
, bool *available
) const
395 case 0x48: { // Accepted cargo types
399 for (cargo_type
= 0; cargo_type
< NUM_CARGO
; cargo_type
++) {
400 if (HasBit(this->goods
[cargo_type
].status
, GoodsEntry::GES_ACCEPTANCE
)) SetBit(value
, cargo_type
);
405 case 0x8A: return this->had_vehicle_of_type
;
406 case 0xF1: return (this->airport
.tile
!= INVALID_TILE
) ? this->airport
.GetSpec()->ttd_airport_type
: ATP_TTDP_LARGE
;
407 case 0xF2: return (this->truck_stops
!= nullptr) ? this->truck_stops
->status
: 0;
408 case 0xF3: return (this->bus_stops
!= nullptr) ? this->bus_stops
->status
: 0;
409 case 0xF6: return this->airport
.flags
;
410 case 0xF7: return GB(this->airport
.flags
, 8, 8);
413 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
414 if ((variable
>= 0x60 && variable
<= 0x65) || variable
== 0x69) {
415 CargoID c
= GetCargoTranslation(parameter
, object
.grffile
);
417 if (c
== CT_INVALID
) {
419 case 0x62: return 0xFFFFFFFF;
420 case 0x64: return 0xFF00;
424 const GoodsEntry
*ge
= &this->goods
[c
];
427 case 0x60: return std::min(ge
->cargo
.TotalCount(), 4095u);
428 case 0x61: return ge
->HasVehicleEverTriedLoading() ? ge
->time_since_pickup
: 0;
429 case 0x62: return ge
->HasRating() ? ge
->rating
: 0xFFFFFFFF;
430 case 0x63: return ge
->cargo
.DaysInTransit();
431 case 0x64: return ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
| (ge
->last_age
<< 8) : 0xFF00;
432 case 0x65: return GB(ge
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 3;
434 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 1 == (int)GoodsEntry::GES_LAST_MONTH
);
435 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 2 == (int)GoodsEntry::GES_CURRENT_MONTH
);
436 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK
);
437 return GB(ge
->status
, GoodsEntry::GES_EVER_ACCEPTED
, 4);
442 /* Handle cargo variables (deprecated) */
443 if (variable
>= 0x8C && variable
<= 0xEC) {
444 const GoodsEntry
*g
= &this->goods
[GB(variable
- 0x8C, 3, 4)];
445 switch (GB(variable
- 0x8C, 0, 3)) {
446 case 0: return g
->cargo
.TotalCount();
447 case 1: return GB(std::min(g
->cargo
.TotalCount(), 4095u), 0, 4) | (GB(g
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 7);
448 case 2: return g
->time_since_pickup
;
449 case 3: return g
->rating
;
450 case 4: return g
->cargo
.Source();
451 case 5: return g
->cargo
.DaysInTransit();
452 case 6: return g
->last_speed
;
453 case 7: return g
->last_age
;
457 Debug(grf
, 1, "Unhandled station variable 0x{:X}", variable
);
463 uint32
Waypoint::GetNewGRFVariable(const ResolverObject
&object
, byte variable
, byte parameter
, bool *available
) const
466 case 0x48: return 0; // Accepted cargo types
467 case 0x8A: return HVOT_WAYPOINT
;
468 case 0xF1: return 0; // airport type
469 case 0xF2: return 0; // truck stop status
470 case 0xF3: return 0; // bus stop status
471 case 0xF6: return 0; // airport flags
472 case 0xF7: return 0; // airport flags cont.
475 /* Handle cargo variables with parameter, 0x60 to 0x65 */
476 if (variable
>= 0x60 && variable
<= 0x65) {
480 /* Handle cargo variables (deprecated) */
481 if (variable
>= 0x8C && variable
<= 0xEC) {
482 switch (GB(variable
- 0x8C, 0, 3)) {
483 case 3: return INITIAL_STATION_RATING
;
484 case 4: return INVALID_STATION
;
489 Debug(grf
, 1, "Unhandled station variable 0x{:X}", variable
);
495 /* virtual */ const SpriteGroup
*StationResolverObject::ResolveReal(const RealSpriteGroup
*group
) const
497 if (this->station_scope
.st
== nullptr || this->station_scope
.statspec
->cls_id
== STAT_CLASS_WAYP
) {
498 return group
->loading
[0];
502 const Station
*st
= Station::From(this->station_scope
.st
);
504 switch (this->station_scope
.cargo_type
) {
512 for (CargoID cargo_type
= 0; cargo_type
< NUM_CARGO
; cargo_type
++) {
513 cargo
+= st
->goods
[cargo_type
].cargo
.TotalCount();
518 cargo
= st
->goods
[this->station_scope
.cargo_type
].cargo
.TotalCount();
522 if (HasBit(this->station_scope
.statspec
->flags
, SSF_DIV_BY_STATION_SIZE
)) cargo
/= (st
->train_station
.w
+ st
->train_station
.h
);
523 cargo
= std::min(0xfffu
, cargo
);
525 if (cargo
> this->station_scope
.statspec
->cargo_threshold
) {
526 if (!group
->loading
.empty()) {
527 uint set
= ((cargo
- this->station_scope
.statspec
->cargo_threshold
) * (uint
)group
->loading
.size()) / (4096 - this->station_scope
.statspec
->cargo_threshold
);
528 return group
->loading
[set
];
531 if (!group
->loaded
.empty()) {
532 uint set
= (cargo
* (uint
)group
->loaded
.size()) / (this->station_scope
.statspec
->cargo_threshold
+ 1);
533 return group
->loaded
[set
];
537 return group
->loading
[0];
540 GrfSpecFeature
StationResolverObject::GetFeature() const
545 uint32
StationResolverObject::GetDebugID() const
547 return this->station_scope
.statspec
->grf_prop
.local_id
;
551 * Resolver for stations.
552 * @param statspec Station (type) specification.
553 * @param base_station Instance of the station.
554 * @param tile %Tile of the station.
555 * @param callback Callback ID.
556 * @param callback_param1 First parameter (var 10) of the callback.
557 * @param callback_param2 Second parameter (var 18) of the callback.
559 StationResolverObject::StationResolverObject(const StationSpec
*statspec
, BaseStation
*base_station
, TileIndex tile
,
560 CallbackID callback
, uint32 callback_param1
, uint32 callback_param2
)
561 : ResolverObject(statspec
->grf_prop
.grffile
, callback
, callback_param1
, callback_param2
),
562 station_scope(*this, statspec
, base_station
, tile
), town_scope(nullptr)
564 /* Invalidate all cached vars */
567 CargoID ctype
= CT_DEFAULT_NA
;
569 if (this->station_scope
.st
== nullptr) {
570 /* No station, so we are in a purchase list */
572 } else if (Station::IsExpected(this->station_scope
.st
)) {
573 const Station
*st
= Station::From(this->station_scope
.st
);
574 /* Pick the first cargo that we have waiting */
575 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
576 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[cs
->Index()] != nullptr &&
577 st
->goods
[cs
->Index()].cargo
.TotalCount() > 0) {
584 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[ctype
] == nullptr) {
588 /* Remember the cargo type we've picked */
589 this->station_scope
.cargo_type
= ctype
;
590 this->root_spritegroup
= this->station_scope
.statspec
->grf_prop
.spritegroup
[this->station_scope
.cargo_type
];
593 StationResolverObject::~StationResolverObject()
595 delete this->town_scope
;
599 * Resolve sprites for drawing a station tile.
600 * @param statspec Station spec
601 * @param st Station (nullptr in GUI)
602 * @param tile Station tile being drawn (INVALID_TILE in GUI)
603 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
604 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
606 SpriteID
GetCustomStationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint32 var10
)
608 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, var10
);
609 const SpriteGroup
*group
= object
.Resolve();
610 if (group
== nullptr || group
->type
!= SGT_RESULT
) return 0;
611 return group
->GetResult() - 0x42D;
615 * Resolve the sprites for custom station foundations.
616 * @param statspec Station spec
618 * @param tile Station tile being drawn
619 * @param layout Spritelayout as returned by previous callback
620 * @param edge_info Information about northern tile edges; whether they need foundations or merge into adjacent tile's foundations.
621 * @return First sprite of a set of foundation sprites for various slopes, or 0 if default foundations shall be drawn.
623 SpriteID
GetCustomStationFoundationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint layout
, uint edge_info
)
625 /* callback_param1 == 2 means we are resolving the foundation sprites. */
626 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, 2, layout
| (edge_info
<< 16));
628 const SpriteGroup
*group
= object
.Resolve();
629 if (group
== nullptr || group
->type
!= SGT_RESULT
) return 0;
631 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
632 return group
->GetResult() + GetRegister(0x100);
636 uint16
GetStationCallback(CallbackID callback
, uint32 param1
, uint32 param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
)
638 StationResolverObject
object(statspec
, st
, tile
, callback
, param1
, param2
);
639 return object
.ResolveCallback();
643 * Check the slope of a tile of a new station.
644 * @param north_tile Norther tile of the station rect.
645 * @param cur_tile Tile to check.
646 * @param statspec Station spec.
647 * @param axis Axis of the new station.
648 * @param plat_len Platform length.
649 * @param numtracks Number of platforms.
650 * @return Succeeded or failed command.
652 CommandCost
PerformStationTileSlopeCheck(TileIndex north_tile
, TileIndex cur_tile
, const StationSpec
*statspec
, Axis axis
, byte plat_len
, byte numtracks
)
654 TileIndexDiff diff
= cur_tile
- north_tile
;
655 Slope slope
= GetTileSlope(cur_tile
);
657 StationResolverObject
object(statspec
, nullptr, cur_tile
, CBID_STATION_LAND_SLOPE_CHECK
,
658 (slope
<< 4) | (slope
^ (axis
== AXIS_Y
&& HasBit(slope
, CORNER_W
) != HasBit(slope
, CORNER_E
) ? SLOPE_EW
: 0)),
659 (numtracks
<< 24) | (plat_len
<< 16) | (axis
== AXIS_Y
? TileX(diff
) << 8 | TileY(diff
) : TileY(diff
) << 8 | TileX(diff
)));
660 object
.station_scope
.axis
= axis
;
662 uint16 cb_res
= object
.ResolveCallback();
664 /* Failed callback means success. */
665 if (cb_res
== CALLBACK_FAILED
) return CommandCost();
667 /* The meaning of bit 10 is inverted for a grf version < 8. */
668 if (statspec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(cb_res
, 10);
669 return GetErrorMessageFromLocationCallbackResult(cb_res
, statspec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
674 * Allocate a StationSpec to a Station. This is called once per build operation.
675 * @param statspec StationSpec to allocate.
676 * @param st Station to allocate it to.
677 * @param exec Whether to actually allocate the spec.
678 * @return Index within the Station's spec list, or -1 if the allocation failed.
680 int AllocateSpecToStation(const StationSpec
*statspec
, BaseStation
*st
, bool exec
)
684 if (statspec
== nullptr || st
== nullptr) return 0;
686 for (i
= 1; i
< st
->num_specs
&& i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
687 if (st
->speclist
[i
].spec
== nullptr && st
->speclist
[i
].grfid
== 0) break;
690 if (i
== NUM_STATIONSSPECS_PER_STATION
) {
691 /* As final effort when the spec list is already full...
692 * try to find the same spec and return that one. This might
693 * result in slightly "wrong" (as per specs) looking stations,
694 * but it's fairly unlikely that one reaches the limit anyways.
696 for (i
= 1; i
< st
->num_specs
&& i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
697 if (st
->speclist
[i
].spec
== statspec
) return i
;
704 if (i
>= st
->num_specs
) {
705 st
->num_specs
= i
+ 1;
706 st
->speclist
= ReallocT(st
->speclist
, st
->num_specs
);
708 if (st
->num_specs
== 2) {
709 /* Initial allocation */
710 st
->speclist
[0].spec
= nullptr;
711 st
->speclist
[0].grfid
= 0;
712 st
->speclist
[0].localidx
= 0;
716 st
->speclist
[i
].spec
= statspec
;
717 st
->speclist
[i
].grfid
= statspec
->grf_prop
.grffile
->grfid
;
718 st
->speclist
[i
].localidx
= statspec
->grf_prop
.local_id
;
720 StationUpdateCachedTriggers(st
);
728 * Deallocate a StationSpec from a Station. Called when removing a single station tile.
729 * @param st Station to work with.
730 * @param specindex Index of the custom station within the Station's spec list.
731 * @return Indicates whether the StationSpec was deallocated.
733 void DeallocateSpecFromStation(BaseStation
*st
, byte specindex
)
735 /* specindex of 0 (default) is never freeable */
736 if (specindex
== 0) return;
738 ETileArea area
= ETileArea(st
, INVALID_TILE
, TA_WHOLE
);
739 /* Check all tiles over the station to check if the specindex is still in use */
740 for (TileIndex tile
: area
) {
741 if (st
->TileBelongsToRailStation(tile
) && GetCustomStationSpecIndex(tile
) == specindex
) {
746 /* This specindex is no longer in use, so deallocate it */
747 st
->speclist
[specindex
].spec
= nullptr;
748 st
->speclist
[specindex
].grfid
= 0;
749 st
->speclist
[specindex
].localidx
= 0;
751 /* If this was the highest spec index, reallocate */
752 if (specindex
== st
->num_specs
- 1) {
753 for (; st
->speclist
[st
->num_specs
- 1].grfid
== 0 && st
->num_specs
> 1; st
->num_specs
--) {}
755 if (st
->num_specs
> 1) {
756 st
->speclist
= ReallocT(st
->speclist
, st
->num_specs
);
760 st
->speclist
= nullptr;
761 st
->cached_anim_triggers
= 0;
762 st
->cached_cargo_triggers
= 0;
767 StationUpdateCachedTriggers(st
);
771 * Draw representation of a station tile for GUI purposes.
772 * @param x Position x of image.
773 * @param y Position y of image.
775 * @param railtype Rail type.
776 * @param sclass, station Type of station.
777 * @param station station ID
778 * @return True if the tile was drawn (allows for fallback to default graphic)
780 bool DrawStationTile(int x
, int y
, RailType railtype
, Axis axis
, StationClassID sclass
, uint station
)
782 const DrawTileSprites
*sprites
= nullptr;
783 const RailtypeInfo
*rti
= GetRailTypeInfo(railtype
);
784 PaletteID palette
= COMPANY_SPRITE_COLOUR(_local_company
);
787 const StationSpec
*statspec
= StationClass::Get(sclass
)->GetSpec(station
);
788 if (statspec
== nullptr) return false;
790 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
791 uint16 callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, nullptr, INVALID_TILE
);
792 if (callback
!= CALLBACK_FAILED
) tile
= callback
& ~1;
795 uint32 total_offset
= rti
->GetRailtypeSpriteOffset();
796 uint32 relocation
= 0;
797 uint32 ground_relocation
= 0;
798 const NewGRFSpriteLayout
*layout
= nullptr;
799 DrawTileSprites tmp_rail_layout
;
801 if (statspec
->renderdata
.empty()) {
802 sprites
= GetStationTileLayout(STATION_RAIL
, tile
+ axis
);
804 layout
= &statspec
->renderdata
[(tile
< statspec
->renderdata
.size()) ? tile
+ axis
: (uint
)axis
];
805 if (!layout
->NeedsPreprocessing()) {
811 if (layout
!= nullptr) {
812 /* Sprite layout which needs preprocessing */
813 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
814 uint32 var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
815 for (uint8 var10
: SetBitIterator(var10_values
)) {
816 uint32 var10_relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, var10
);
817 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
820 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
821 sprites
= &tmp_rail_layout
;
824 /* Simple sprite layout */
825 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, 0);
826 if (HasBit(sprites
->ground
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) {
827 ground_relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, 1);
829 ground_relocation
+= rti
->fallback_railtype
;
832 SpriteID image
= sprites
->ground
.sprite
;
833 PaletteID pal
= sprites
->ground
.pal
;
834 RailTrackOffset overlay_offset
;
835 if (rti
->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &image
, &overlay_offset
)) {
836 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
837 DrawSprite(image
, PAL_NONE
, x
, y
);
838 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
840 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
841 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
842 DrawSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
), x
, y
);
845 DrawRailTileSeqInGUI(x
, y
, sprites
, total_offset
, relocation
, palette
);
851 const StationSpec
*GetStationSpec(TileIndex t
)
853 if (!IsCustomStationSpecIndex(t
)) return nullptr;
855 const BaseStation
*st
= BaseStation::GetByTile(t
);
856 uint specindex
= GetCustomStationSpecIndex(t
);
857 return specindex
< st
->num_specs
? st
->speclist
[specindex
].spec
: nullptr;
862 * Check whether a rail station tile is NOT traversable.
863 * @param tile %Tile to test.
864 * @return Station tile is blocked.
865 * @note This could be cached (during build) in the map array to save on all the dereferencing.
867 bool IsStationTileBlocked(TileIndex tile
)
869 const StationSpec
*statspec
= GetStationSpec(tile
);
871 return statspec
!= nullptr && HasBit(statspec
->blocked
, GetStationGfx(tile
));
875 * Check if a rail station tile shall have pylons when electrified.
876 * @param tile %Tile to test.
877 * @return Tile shall have pylons.
878 * @note This could be cached (during build) in the map array to save on all the dereferencing.
880 bool CanStationTileHavePylons(TileIndex tile
)
882 const StationSpec
*statspec
= GetStationSpec(tile
);
883 uint gfx
= GetStationGfx(tile
);
884 /* Default stations do not draw pylons under roofs (gfx >= 4) */
885 return statspec
!= nullptr ? HasBit(statspec
->pylons
, gfx
) : gfx
< 4;
889 * Check if a rail station tile shall have wires when electrified.
890 * @param tile %Tile to test.
891 * @return Tile shall have wires.
892 * @note This could be cached (during build) in the map array to save on all the dereferencing.
894 bool CanStationTileHaveWires(TileIndex tile
)
896 const StationSpec
*statspec
= GetStationSpec(tile
);
897 return statspec
== nullptr || !HasBit(statspec
->wires
, GetStationGfx(tile
));
900 /** Wrapper for animation control, see GetStationCallback. */
901 uint16
GetAnimStationCallback(CallbackID callback
, uint32 param1
, uint32 param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, int extra_data
)
903 return GetStationCallback(callback
, param1
, param2
, statspec
, st
, tile
);
906 /** Helper class for animation control. */
907 struct StationAnimationBase
: public AnimationBase
<StationAnimationBase
, StationSpec
, BaseStation
, int, GetAnimStationCallback
> {
908 static const CallbackID cb_animation_speed
= CBID_STATION_ANIMATION_SPEED
;
909 static const CallbackID cb_animation_next_frame
= CBID_STATION_ANIM_NEXT_FRAME
;
911 static const StationCallbackMask cbm_animation_speed
= CBM_STATION_ANIMATION_SPEED
;
912 static const StationCallbackMask cbm_animation_next_frame
= CBM_STATION_ANIMATION_NEXT_FRAME
;
915 void AnimateStationTile(TileIndex tile
)
917 const StationSpec
*ss
= GetStationSpec(tile
);
918 if (ss
== nullptr) return;
920 StationAnimationBase::AnimateTile(ss
, BaseStation::GetByTile(tile
), tile
, HasBit(ss
->flags
, SSF_CB141_RANDOM_BITS
));
923 void TriggerStationAnimation(BaseStation
*st
, TileIndex trigger_tile
, StationAnimationTrigger trigger
, CargoID cargo_type
)
925 /* List of coverage areas for each animation trigger */
926 static const TriggerArea tas
[] = {
927 TA_TILE
, TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_WHOLE
930 /* Get Station if it wasn't supplied */
931 if (st
== nullptr) st
= BaseStation::GetByTile(trigger_tile
);
933 /* Check the cached animation trigger bitmask to see if we need
934 * to bother with any further processing. */
935 if (!HasBit(st
->cached_anim_triggers
, trigger
)) return;
937 uint16 random_bits
= Random();
938 ETileArea area
= ETileArea(st
, trigger_tile
, tas
[trigger
]);
940 /* Check all tiles over the station to check if the specindex is still in use */
941 for (TileIndex tile
: area
) {
942 if (st
->TileBelongsToRailStation(tile
)) {
943 const StationSpec
*ss
= GetStationSpec(tile
);
944 if (ss
!= nullptr && HasBit(ss
->animation
.triggers
, trigger
)) {
946 if (cargo_type
== CT_INVALID
) {
949 cargo
= ss
->grf_prop
.grffile
->cargo_map
[cargo_type
];
951 StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP
, ss
, st
, tile
, (random_bits
<< 16) | GB(Random(), 0, 16), (uint8
)trigger
| (cargo
<< 8));
958 * Trigger station randomisation
959 * @param st station being triggered
960 * @param trigger_tile specific tile of platform to trigger
961 * @param trigger trigger type
962 * @param cargo_type cargo type causing trigger
964 void TriggerStationRandomisation(Station
*st
, TileIndex trigger_tile
, StationRandomTrigger trigger
, CargoID cargo_type
)
966 /* List of coverage areas for each animation trigger */
967 static const TriggerArea tas
[] = {
968 TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
971 /* Get Station if it wasn't supplied */
972 if (st
== nullptr) st
= Station::GetByTile(trigger_tile
);
974 /* Check the cached cargo trigger bitmask to see if we need
975 * to bother with any further processing. */
976 if (st
->cached_cargo_triggers
== 0) return;
977 if (cargo_type
!= CT_INVALID
&& !HasBit(st
->cached_cargo_triggers
, cargo_type
)) return;
979 uint32 whole_reseed
= 0;
980 ETileArea area
= ETileArea(st
, trigger_tile
, tas
[trigger
]);
982 CargoTypes empty_mask
= 0;
983 if (trigger
== SRT_CARGO_TAKEN
) {
984 /* Create a bitmask of completely empty cargo types to be matched */
985 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
986 if (st
->goods
[i
].cargo
.TotalCount() == 0) {
987 SetBit(empty_mask
, i
);
992 /* Store triggers now for var 5F */
993 SetBit(st
->waiting_triggers
, trigger
);
994 uint32 used_triggers
= 0;
996 /* Check all tiles over the station to check if the specindex is still in use */
997 for (TileIndex tile
: area
) {
998 if (st
->TileBelongsToRailStation(tile
)) {
999 const StationSpec
*ss
= GetStationSpec(tile
);
1000 if (ss
== nullptr) continue;
1002 /* Cargo taken "will only be triggered if all of those
1003 * cargo types have no more cargo waiting." */
1004 if (trigger
== SRT_CARGO_TAKEN
) {
1005 if ((ss
->cargo_triggers
& ~empty_mask
) != 0) continue;
1008 if (cargo_type
== CT_INVALID
|| HasBit(ss
->cargo_triggers
, cargo_type
)) {
1009 StationResolverObject
object(ss
, st
, tile
, CBID_RANDOM_TRIGGER
, 0);
1010 object
.waiting_triggers
= st
->waiting_triggers
;
1012 const SpriteGroup
*group
= object
.Resolve();
1013 if (group
== nullptr) continue;
1015 used_triggers
|= object
.used_triggers
;
1017 uint32 reseed
= object
.GetReseedSum();
1019 whole_reseed
|= reseed
;
1022 /* Set individual tile random bits */
1023 uint8 random_bits
= GetStationTileRandomBits(tile
);
1024 random_bits
&= ~reseed
;
1025 random_bits
|= Random() & reseed
;
1026 SetStationTileRandomBits(tile
, random_bits
);
1028 MarkTileDirtyByTile(tile
);
1034 /* Update whole station random bits */
1035 st
->waiting_triggers
&= ~used_triggers
;
1036 if ((whole_reseed
& 0xFFFF) != 0) {
1037 st
->random_bits
&= ~whole_reseed
;
1038 st
->random_bits
|= Random() & whole_reseed
;
1043 * Update the cached animation trigger bitmask for a station.
1044 * @param st Station to update.
1046 void StationUpdateCachedTriggers(BaseStation
*st
)
1048 st
->cached_anim_triggers
= 0;
1049 st
->cached_cargo_triggers
= 0;
1051 /* Combine animation trigger bitmask for all station specs
1052 * of this station. */
1053 for (uint i
= 0; i
< st
->num_specs
; i
++) {
1054 const StationSpec
*ss
= st
->speclist
[i
].spec
;
1055 if (ss
!= nullptr) {
1056 st
->cached_anim_triggers
|= ss
->animation
.triggers
;
1057 st
->cached_cargo_triggers
|= ss
->cargo_triggers
;