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"
26 #include "timer/timer_game_calendar.h"
28 #include "safeguards.h"
31 template <typename Tspec
, typename Tid
, Tid Tmax
>
32 /* static */ void NewGRFClass
<Tspec
, Tid
, Tmax
>::InsertDefaults()
34 /* Set up initial data */
35 StationClass::Get(StationClass::Allocate('DFLT'))->name
= STR_STATION_CLASS_DFLT
;
36 StationClass::Get(StationClass::Allocate('DFLT'))->Insert(nullptr);
37 StationClass::Get(StationClass::Allocate('WAYP'))->name
= STR_STATION_CLASS_WAYP
;
38 StationClass::Get(StationClass::Allocate('WAYP'))->Insert(nullptr);
41 template <typename Tspec
, typename Tid
, Tid Tmax
>
42 bool NewGRFClass
<Tspec
, Tid
, Tmax
>::IsUIAvailable(uint
) const
47 INSTANTIATE_NEWGRF_CLASS_METHODS(StationClass
, StationSpec
, StationClassID
, STAT_CLASS_MAX
)
49 static const uint NUM_STATIONSSPECS_PER_STATION
= 255; ///< Maximum number of parts per station.
57 struct ETileArea
: TileArea
{
58 ETileArea(const BaseStation
*st
, TileIndex tile
, TriggerArea ta
)
61 default: NOT_REACHED();
71 Axis axis
= GetRailStationAxis(tile
);
72 TileIndexDiff delta
= TileOffsByDiagDir(AxisToDiagDir(axis
));
74 for (end
= tile
; IsRailStationTile(end
+ delta
) && IsCompatibleTrainStationTile(end
+ delta
, tile
); end
+= delta
) { /* Nothing */ }
75 for (start
= tile
; IsRailStationTile(start
- delta
) && IsCompatibleTrainStationTile(start
- delta
, tile
); start
-= delta
) { /* Nothing */ }
78 this->w
= TileX(end
) - TileX(start
) + 1;
79 this->h
= TileY(end
) - TileY(start
) + 1;
84 st
->GetTileArea(this, Station::IsExpected(st
) ? STATION_RAIL
: STATION_WAYPOINT
);
92 * Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
93 * if not centered: .TNLcCpP, if centered: .TNL..CP
94 * - T = Tile layout number (#GetStationGfx)
95 * - N = Number of platforms
96 * - L = Length of platforms
97 * - C = Current platform number from start, c = from end
98 * - P = Position along platform from start, p = from end
100 * if centered, C/P start from the centre and c/p are not available.
101 * @return Platform information in bit-stuffed format.
103 uint32_t GetPlatformInfo(Axis axis
, byte tile
, int platforms
, int length
, int x
, int y
, bool centred
)
107 if (axis
== AXIS_X
) {
108 Swap(platforms
, length
);
117 SB(retval
, 0, 4, y
& 0xF);
118 SB(retval
, 4, 4, x
& 0xF);
120 SB(retval
, 0, 4, std::min(15, y
));
121 SB(retval
, 4, 4, std::min(15, length
- y
- 1));
122 SB(retval
, 8, 4, std::min(15, x
));
123 SB(retval
, 12, 4, std::min(15, platforms
- x
- 1));
125 SB(retval
, 16, 4, std::min(15, length
));
126 SB(retval
, 20, 4, std::min(15, platforms
));
127 SB(retval
, 24, 4, tile
);
134 * Find the end of a railway station, from the \a tile, in the direction of \a delta.
135 * @param tile Start tile.
136 * @param delta Movement direction.
137 * @param check_type Stop when the custom station type changes.
138 * @param check_axis Stop when the station direction changes.
139 * @return Found end of the railway station.
141 static TileIndex
FindRailStationEnd(TileIndex tile
, TileIndexDiff delta
, bool check_type
, bool check_axis
)
144 Axis orig_axis
= AXIS_X
;
145 StationID sid
= GetStationIndex(tile
);
147 if (check_type
) orig_type
= GetCustomStationSpecIndex(tile
);
148 if (check_axis
) orig_axis
= GetRailStationAxis(tile
);
151 TileIndex new_tile
= TILE_ADD(tile
, delta
);
153 if (!IsTileType(new_tile
, MP_STATION
) || GetStationIndex(new_tile
) != sid
) break;
154 if (!HasStationRail(new_tile
)) break;
155 if (check_type
&& GetCustomStationSpecIndex(new_tile
) != orig_type
) break;
156 if (check_axis
&& GetRailStationAxis(new_tile
) != orig_axis
) break;
164 static uint32_t GetPlatformInfoHelper(TileIndex tile
, bool check_type
, bool check_axis
, bool centred
)
166 int tx
= TileX(tile
);
167 int ty
= TileY(tile
);
168 int sx
= TileX(FindRailStationEnd(tile
, TileDiffXY(-1, 0), check_type
, check_axis
));
169 int sy
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, -1), check_type
, check_axis
));
170 int ex
= TileX(FindRailStationEnd(tile
, TileDiffXY( 1, 0), check_type
, check_axis
)) + 1;
171 int ey
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, 1), check_type
, check_axis
)) + 1;
176 return GetPlatformInfo(GetRailStationAxis(tile
), GetStationGfx(tile
), ex
, ey
, tx
, ty
, centred
);
180 static uint32_t GetRailContinuationInfo(TileIndex tile
)
182 /* Tile offsets and exit dirs for X axis */
183 static const Direction x_dir
[8] = { DIR_SW
, DIR_NE
, DIR_SE
, DIR_NW
, DIR_S
, DIR_E
, DIR_W
, DIR_N
};
184 static const DiagDirection x_exits
[8] = { DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SW
, DIAGDIR_NE
};
186 /* Tile offsets and exit dirs for Y axis */
187 static const Direction y_dir
[8] = { DIR_SE
, DIR_NW
, DIR_SW
, DIR_NE
, DIR_S
, DIR_W
, DIR_E
, DIR_N
};
188 static const DiagDirection y_exits
[8] = { DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SW
, DIAGDIR_NE
, DIAGDIR_SE
, DIAGDIR_NW
, DIAGDIR_SE
, DIAGDIR_NW
};
190 Axis axis
= GetRailStationAxis(tile
);
192 /* Choose appropriate lookup table to use */
193 const Direction
*dir
= axis
== AXIS_X
? x_dir
: y_dir
;
194 const DiagDirection
*diagdir
= axis
== AXIS_X
? x_exits
: y_exits
;
199 for (i
= 0; i
< lengthof(x_dir
); i
++, dir
++, diagdir
++) {
200 TileIndex neighbour_tile
= tile
+ TileOffsByDir(*dir
);
201 TrackBits trackbits
= TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile
, TRANSPORT_RAIL
, 0));
202 if (trackbits
!= TRACK_BIT_NONE
) {
203 /* If there is any track on the tile, set the bit in the second byte */
206 /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
207 * with the next tile because the ramp is not going in the right direction. */
208 if (IsTileType(neighbour_tile
, MP_TUNNELBRIDGE
) && GetTunnelBridgeDirection(neighbour_tile
) != *diagdir
) {
212 /* If any track reaches our exit direction, set the bit in the lower byte */
213 if (trackbits
& DiagdirReachesTracks(*diagdir
)) SetBit(res
, i
);
221 /* Station Resolver Functions */
222 /* virtual */ uint32_t StationScopeResolver::GetRandomBits() const
224 return (this->st
== nullptr ? 0 : this->st
->random_bits
) | (this->tile
== INVALID_TILE
? 0 : GetStationTileRandomBits(this->tile
) << 16);
228 /* virtual */ uint32_t StationScopeResolver::GetTriggers() const
230 return this->st
== nullptr ? 0 : this->st
->waiting_triggers
;
235 * Station variable cache
236 * This caches 'expensive' station variable lookups which iterate over
237 * several tiles that may be called multiple times per Resolve().
246 uint8_t valid
; ///< Bits indicating what variable is valid (for each bit, \c 0 is invalid, \c 1 is valid).
250 * Get the town scope associated with a station, if it exists.
251 * On the first call, the town scope is created (if possible).
252 * @return Town scope, if available.
254 TownScopeResolver
*StationResolverObject::GetTown()
256 if (this->town_scope
== nullptr) {
258 if (this->station_scope
.st
!= nullptr) {
259 t
= this->station_scope
.st
->town
;
260 } else if (this->station_scope
.tile
!= INVALID_TILE
) {
261 t
= ClosestTownFromTile(this->station_scope
.tile
, UINT_MAX
);
263 if (t
== nullptr) return nullptr;
264 this->town_scope
= new TownScopeResolver(*this, t
, this->station_scope
.st
== nullptr);
266 return this->town_scope
;
269 /* virtual */ uint32_t StationScopeResolver::GetVariable(byte variable
, [[maybe_unused
]] uint32_t parameter
, bool *available
) const
271 if (this->st
== nullptr) {
272 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
278 case 0x49: return 0x2110000; // Platforms, tracks & position
279 case 0x42: return 0; // Rail type (XXX Get current type from GUI?)
280 case 0x43: return GetCompanyInfo(_current_company
); // Station owner
281 case 0x44: return 2; // PBS status
282 case 0x67: // Land info of nearby tile
283 if (this->axis
!= INVALID_AXIS
&& this->tile
!= INVALID_TILE
) {
284 TileIndex tile
= this->tile
;
285 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
, true, this->axis
); // only perform if it is required
287 Slope tileh
= GetTileSlope(tile
);
288 bool swap
= (this->axis
== AXIS_Y
&& HasBit(tileh
, CORNER_W
) != HasBit(tileh
, CORNER_E
));
290 return GetNearbyTileInformation(tile
, this->ro
.grffile
->grf_version
>= 8) ^ (swap
? SLOPE_EW
: 0);
294 case 0xFA: return ClampTo
<uint16_t>(TimerGameCalendar::date
- CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR
); // Build date, clamped to a 16 bit value
302 /* Calculated station variables */
304 if (!HasBit(_svc
.valid
, 0)) { _svc
.v40
= GetPlatformInfoHelper(this->tile
, false, false, false); SetBit(_svc
.valid
, 0); }
308 if (!HasBit(_svc
.valid
, 1)) { _svc
.v41
= GetPlatformInfoHelper(this->tile
, true, false, false); SetBit(_svc
.valid
, 1); }
311 case 0x42: return GetTerrainType(this->tile
) | (GetReverseRailTypeTranslation(GetRailType(this->tile
), this->statspec
->grf_prop
.grffile
) << 8);
312 case 0x43: return GetCompanyInfo(this->st
->owner
); // Station owner
313 case 0x44: return HasStationReservation(this->tile
) ? 7 : 4; // PBS status
315 if (!HasBit(_svc
.valid
, 2)) { _svc
.v45
= GetRailContinuationInfo(this->tile
); SetBit(_svc
.valid
, 2); }
319 if (!HasBit(_svc
.valid
, 3)) { _svc
.v46
= GetPlatformInfoHelper(this->tile
, false, false, true); SetBit(_svc
.valid
, 3); }
323 if (!HasBit(_svc
.valid
, 4)) { _svc
.v47
= GetPlatformInfoHelper(this->tile
, true, false, true); SetBit(_svc
.valid
, 4); }
327 if (!HasBit(_svc
.valid
, 5)) { _svc
.v49
= GetPlatformInfoHelper(this->tile
, false, true, false); SetBit(_svc
.valid
, 5); }
330 case 0x4A: // Animation frame of tile
331 return GetAnimationFrame(this->tile
);
333 /* Variables which use the parameter */
334 /* Variables 0x60 to 0x65 and 0x69 are handled separately below */
335 case 0x66: { // Animation frame of nearby tile
336 TileIndex tile
= this->tile
;
337 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
);
338 return this->st
->TileBelongsToRailStation(tile
) ? GetAnimationFrame(tile
) : UINT_MAX
;
341 case 0x67: { // Land info of nearby tile
342 Axis axis
= GetRailStationAxis(this->tile
);
343 TileIndex tile
= this->tile
;
344 if (parameter
!= 0) tile
= GetNearbyTile(parameter
, tile
); // only perform if it is required
346 Slope tileh
= GetTileSlope(tile
);
347 bool swap
= (axis
== AXIS_Y
&& HasBit(tileh
, CORNER_W
) != HasBit(tileh
, CORNER_E
));
349 return GetNearbyTileInformation(tile
, this->ro
.grffile
->grf_version
>= 8) ^ (swap
? SLOPE_EW
: 0);
352 case 0x68: { // Station info of nearby tiles
353 TileIndex nearby_tile
= GetNearbyTile(parameter
, this->tile
);
355 if (!HasStationTileRail(nearby_tile
)) return 0xFFFFFFFF;
357 uint32_t grfid
= this->st
->speclist
[GetCustomStationSpecIndex(this->tile
)].grfid
;
358 bool perpendicular
= GetRailStationAxis(this->tile
) != GetRailStationAxis(nearby_tile
);
359 bool same_station
= this->st
->TileBelongsToRailStation(nearby_tile
);
360 uint32_t res
= GB(GetStationGfx(nearby_tile
), 1, 2) << 12 | !!perpendicular
<< 11 | !!same_station
<< 10;
362 if (IsCustomStationSpecIndex(nearby_tile
)) {
363 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[GetCustomStationSpecIndex(nearby_tile
)];
364 res
|= 1 << (ssl
.grfid
!= grfid
? 9 : 8) | ClampTo
<uint8_t>(ssl
.localidx
);
369 case 0x6A: { // GRFID of nearby station tiles
370 TileIndex nearby_tile
= GetNearbyTile(parameter
, this->tile
);
372 if (!HasStationTileRail(nearby_tile
)) return 0xFFFFFFFF;
373 if (!IsCustomStationSpecIndex(nearby_tile
)) return 0;
375 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[GetCustomStationSpecIndex(nearby_tile
)];
379 case 0x6B: { // 16 bit Station ID of nearby tiles
380 TileIndex nearby_tile
= GetNearbyTile(parameter
, this->tile
);
382 if (!HasStationTileRail(nearby_tile
)) return 0xFFFFFFFF;
383 if (!IsCustomStationSpecIndex(nearby_tile
)) return 0xFFFE;
385 uint32_t grfid
= this->st
->speclist
[GetCustomStationSpecIndex(this->tile
)].grfid
;
387 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[GetCustomStationSpecIndex(nearby_tile
)];
388 if (ssl
.grfid
== grfid
) {
395 /* General station variables */
396 case 0x82: return 50;
397 case 0x84: return this->st
->string_id
;
399 case 0xF0: return this->st
->facilities
;
400 case 0xFA: return ClampTo
<uint16_t>(this->st
->build_date
- CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR
);
403 return this->st
->GetNewGRFVariable(this->ro
, variable
, parameter
, available
);
406 uint32_t Station::GetNewGRFVariable(const ResolverObject
&object
, byte variable
, byte parameter
, bool *available
) const
409 case 0x48: { // Accepted cargo types
410 uint32_t value
= GetAcceptanceMask(this);
414 case 0x8A: return this->had_vehicle_of_type
;
415 case 0xF1: return (this->airport
.tile
!= INVALID_TILE
) ? this->airport
.GetSpec()->ttd_airport_type
: ATP_TTDP_LARGE
;
416 case 0xF2: return (this->truck_stops
!= nullptr) ? this->truck_stops
->status
: 0;
417 case 0xF3: return (this->bus_stops
!= nullptr) ? this->bus_stops
->status
: 0;
418 case 0xF6: return this->airport
.flags
;
419 case 0xF7: return GB(this->airport
.flags
, 8, 8);
422 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
423 if ((variable
>= 0x60 && variable
<= 0x65) || variable
== 0x69) {
424 CargoID c
= GetCargoTranslation(parameter
, object
.grffile
);
426 if (!IsValidCargoID(c
)) {
428 case 0x62: return 0xFFFFFFFF;
429 case 0x64: return 0xFF00;
433 const GoodsEntry
*ge
= &this->goods
[c
];
436 case 0x60: return std::min(ge
->cargo
.TotalCount(), 4095u);
437 case 0x61: return ge
->HasVehicleEverTriedLoading() ? ge
->time_since_pickup
: 0;
438 case 0x62: return ge
->HasRating() ? ge
->rating
: 0xFFFFFFFF;
439 case 0x63: return ge
->cargo
.PeriodsInTransit();
440 case 0x64: return ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
| (ge
->last_age
<< 8) : 0xFF00;
441 case 0x65: return GB(ge
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 3;
443 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 1 == (int)GoodsEntry::GES_LAST_MONTH
);
444 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 2 == (int)GoodsEntry::GES_CURRENT_MONTH
);
445 static_assert((int)GoodsEntry::GES_EVER_ACCEPTED
+ 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK
);
446 return GB(ge
->status
, GoodsEntry::GES_EVER_ACCEPTED
, 4);
451 /* Handle cargo variables (deprecated) */
452 if (variable
>= 0x8C && variable
<= 0xEC) {
453 const GoodsEntry
*g
= &this->goods
[GB(variable
- 0x8C, 3, 4)];
454 switch (GB(variable
- 0x8C, 0, 3)) {
455 case 0: return g
->cargo
.TotalCount();
456 case 1: return GB(std::min(g
->cargo
.TotalCount(), 4095u), 0, 4) | (GB(g
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 7);
457 case 2: return g
->time_since_pickup
;
458 case 3: return g
->rating
;
459 case 4: return g
->cargo
.GetFirstStation();
460 case 5: return g
->cargo
.PeriodsInTransit();
461 case 6: return g
->last_speed
;
462 case 7: return g
->last_age
;
466 Debug(grf
, 1, "Unhandled station variable 0x{:X}", variable
);
472 uint32_t Waypoint::GetNewGRFVariable(const ResolverObject
&, byte variable
, [[maybe_unused
]] byte parameter
, bool *available
) const
475 case 0x48: return 0; // Accepted cargo types
476 case 0x8A: return HVOT_WAYPOINT
;
477 case 0xF1: return 0; // airport type
478 case 0xF2: return 0; // truck stop status
479 case 0xF3: return 0; // bus stop status
480 case 0xF6: return 0; // airport flags
481 case 0xF7: return 0; // airport flags cont.
484 /* Handle cargo variables with parameter, 0x60 to 0x65 */
485 if (variable
>= 0x60 && variable
<= 0x65) {
489 /* Handle cargo variables (deprecated) */
490 if (variable
>= 0x8C && variable
<= 0xEC) {
491 switch (GB(variable
- 0x8C, 0, 3)) {
492 case 3: return INITIAL_STATION_RATING
;
493 case 4: return INVALID_STATION
;
498 Debug(grf
, 1, "Unhandled station variable 0x{:X}", variable
);
504 /* virtual */ const SpriteGroup
*StationResolverObject::ResolveReal(const RealSpriteGroup
*group
) const
506 if (this->station_scope
.st
== nullptr || this->station_scope
.statspec
->cls_id
== STAT_CLASS_WAYP
) {
507 return group
->loading
[0];
511 const Station
*st
= Station::From(this->station_scope
.st
);
513 switch (this->station_scope
.cargo_type
) {
515 case SpriteGroupCargo::SG_DEFAULT_NA
:
516 case SpriteGroupCargo::SG_PURCHASE
:
520 case SpriteGroupCargo::SG_DEFAULT
:
521 for (const GoodsEntry
&ge
: st
->goods
) {
522 cargo
+= ge
.cargo
.TotalCount();
527 cargo
= st
->goods
[this->station_scope
.cargo_type
].cargo
.TotalCount();
531 if (HasBit(this->station_scope
.statspec
->flags
, SSF_DIV_BY_STATION_SIZE
)) cargo
/= (st
->train_station
.w
+ st
->train_station
.h
);
532 cargo
= std::min(0xfffu
, cargo
);
534 if (cargo
> this->station_scope
.statspec
->cargo_threshold
) {
535 if (!group
->loading
.empty()) {
536 uint set
= ((cargo
- this->station_scope
.statspec
->cargo_threshold
) * (uint
)group
->loading
.size()) / (4096 - this->station_scope
.statspec
->cargo_threshold
);
537 return group
->loading
[set
];
540 if (!group
->loaded
.empty()) {
541 uint set
= (cargo
* (uint
)group
->loaded
.size()) / (this->station_scope
.statspec
->cargo_threshold
+ 1);
542 return group
->loaded
[set
];
546 return group
->loading
[0];
549 GrfSpecFeature
StationResolverObject::GetFeature() const
554 uint32_t StationResolverObject::GetDebugID() const
556 return this->station_scope
.statspec
->grf_prop
.local_id
;
560 * Resolver for stations.
561 * @param statspec Station (type) specification.
562 * @param base_station Instance of the station.
563 * @param tile %Tile of the station.
564 * @param callback Callback ID.
565 * @param callback_param1 First parameter (var 10) of the callback.
566 * @param callback_param2 Second parameter (var 18) of the callback.
568 StationResolverObject::StationResolverObject(const StationSpec
*statspec
, BaseStation
*base_station
, TileIndex tile
,
569 CallbackID callback
, uint32_t callback_param1
, uint32_t callback_param2
)
570 : ResolverObject(statspec
->grf_prop
.grffile
, callback
, callback_param1
, callback_param2
),
571 station_scope(*this, statspec
, base_station
, tile
), town_scope(nullptr)
573 /* Invalidate all cached vars */
576 CargoID ctype
= SpriteGroupCargo::SG_DEFAULT_NA
;
578 if (this->station_scope
.st
== nullptr) {
579 /* No station, so we are in a purchase list */
580 ctype
= SpriteGroupCargo::SG_PURCHASE
;
581 } else if (Station::IsExpected(this->station_scope
.st
)) {
582 const Station
*st
= Station::From(this->station_scope
.st
);
583 /* Pick the first cargo that we have waiting */
584 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
585 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[cs
->Index()] != nullptr &&
586 st
->goods
[cs
->Index()].cargo
.TotalCount() > 0) {
593 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[ctype
] == nullptr) {
594 ctype
= SpriteGroupCargo::SG_DEFAULT
;
597 /* Remember the cargo type we've picked */
598 this->station_scope
.cargo_type
= ctype
;
599 this->root_spritegroup
= this->station_scope
.statspec
->grf_prop
.spritegroup
[this->station_scope
.cargo_type
];
602 StationResolverObject::~StationResolverObject()
604 delete this->town_scope
;
608 * Resolve sprites for drawing a station tile.
609 * @param statspec Station spec
610 * @param st Station (nullptr in GUI)
611 * @param tile Station tile being drawn (INVALID_TILE in GUI)
612 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
613 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
615 SpriteID
GetCustomStationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint32_t var10
)
617 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, var10
);
618 const SpriteGroup
*group
= object
.Resolve();
619 if (group
== nullptr || group
->type
!= SGT_RESULT
) return 0;
620 return group
->GetResult() - 0x42D;
624 * Resolve the sprites for custom station foundations.
625 * @param statspec Station spec
627 * @param tile Station tile being drawn
628 * @param layout Spritelayout as returned by previous callback
629 * @param edge_info Information about northern tile edges; whether they need foundations or merge into adjacent tile's foundations.
630 * @return First sprite of a set of foundation sprites for various slopes, or 0 if default foundations shall be drawn.
632 SpriteID
GetCustomStationFoundationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint layout
, uint edge_info
)
634 /* callback_param1 == 2 means we are resolving the foundation sprites. */
635 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, 2, layout
| (edge_info
<< 16));
637 const SpriteGroup
*group
= object
.Resolve();
638 if (group
== nullptr || group
->type
!= SGT_RESULT
) return 0;
640 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
641 return group
->GetResult() + GetRegister(0x100);
645 uint16_t GetStationCallback(CallbackID callback
, uint32_t param1
, uint32_t param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
)
647 StationResolverObject
object(statspec
, st
, tile
, callback
, param1
, param2
);
648 return object
.ResolveCallback();
652 * Check the slope of a tile of a new station.
653 * @param north_tile Norther tile of the station rect.
654 * @param cur_tile Tile to check.
655 * @param statspec Station spec.
656 * @param axis Axis of the new station.
657 * @param plat_len Platform length.
658 * @param numtracks Number of platforms.
659 * @return Succeeded or failed command.
661 CommandCost
PerformStationTileSlopeCheck(TileIndex north_tile
, TileIndex cur_tile
, const StationSpec
*statspec
, Axis axis
, byte plat_len
, byte numtracks
)
663 TileIndex diff
= cur_tile
- north_tile
;
664 Slope slope
= GetTileSlope(cur_tile
);
666 StationResolverObject
object(statspec
, nullptr, cur_tile
, CBID_STATION_LAND_SLOPE_CHECK
,
667 (slope
<< 4) | (slope
^ (axis
== AXIS_Y
&& HasBit(slope
, CORNER_W
) != HasBit(slope
, CORNER_E
) ? SLOPE_EW
: 0)),
668 (numtracks
<< 24) | (plat_len
<< 16) | (axis
== AXIS_Y
? TileX(diff
) << 8 | TileY(diff
) : TileY(diff
) << 8 | TileX(diff
)));
669 object
.station_scope
.axis
= axis
;
671 uint16_t cb_res
= object
.ResolveCallback();
673 /* Failed callback means success. */
674 if (cb_res
== CALLBACK_FAILED
) return CommandCost();
676 /* The meaning of bit 10 is inverted for a grf version < 8. */
677 if (statspec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(cb_res
, 10);
678 return GetErrorMessageFromLocationCallbackResult(cb_res
, statspec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
683 * Allocate a StationSpec to a Station. This is called once per build operation.
684 * @param statspec StationSpec to allocate.
685 * @param st Station to allocate it to.
686 * @param exec Whether to actually allocate the spec.
687 * @return Index within the Station's spec list, or -1 if the allocation failed.
689 int AllocateSpecToStation(const StationSpec
*statspec
, BaseStation
*st
, bool exec
)
693 if (statspec
== nullptr || st
== nullptr) return 0;
695 for (i
= 1; i
< st
->speclist
.size() && i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
696 if (st
->speclist
[i
].spec
== nullptr && st
->speclist
[i
].grfid
== 0) break;
699 if (i
== NUM_STATIONSSPECS_PER_STATION
) {
700 /* As final effort when the spec list is already full...
701 * try to find the same spec and return that one. This might
702 * result in slightly "wrong" (as per specs) looking stations,
703 * but it's fairly unlikely that one reaches the limit anyways.
705 for (i
= 1; i
< st
->speclist
.size() && i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
706 if (st
->speclist
[i
].spec
== statspec
) return i
;
713 if (i
>= st
->speclist
.size()) st
->speclist
.resize(i
+ 1);
714 st
->speclist
[i
].spec
= statspec
;
715 st
->speclist
[i
].grfid
= statspec
->grf_prop
.grffile
->grfid
;
716 st
->speclist
[i
].localidx
= statspec
->grf_prop
.local_id
;
718 StationUpdateCachedTriggers(st
);
726 * Deallocate a StationSpec from a Station. Called when removing a single station tile.
727 * @param st Station to work with.
728 * @param specindex Index of the custom station within the Station's spec list.
729 * @return Indicates whether the StationSpec was deallocated.
731 void DeallocateSpecFromStation(BaseStation
*st
, byte specindex
)
733 /* specindex of 0 (default) is never freeable */
734 if (specindex
== 0) return;
736 ETileArea area
= ETileArea(st
, INVALID_TILE
, TA_WHOLE
);
737 /* Check all tiles over the station to check if the specindex is still in use */
738 for (TileIndex tile
: area
) {
739 if (st
->TileBelongsToRailStation(tile
) && GetCustomStationSpecIndex(tile
) == specindex
) {
744 /* This specindex is no longer in use, so deallocate it */
745 st
->speclist
[specindex
].spec
= nullptr;
746 st
->speclist
[specindex
].grfid
= 0;
747 st
->speclist
[specindex
].localidx
= 0;
749 /* If this was the highest spec index, reallocate */
750 if (specindex
== st
->speclist
.size() - 1) {
752 for (num_specs
= st
->speclist
.size() - 1; num_specs
> 0; num_specs
--) {
753 if (st
->speclist
[num_specs
].grfid
!= 0) break;
757 st
->speclist
.resize(num_specs
+ 1);
759 st
->speclist
.clear();
760 st
->cached_anim_triggers
= 0;
761 st
->cached_cargo_triggers
= 0;
766 StationUpdateCachedTriggers(st
);
770 * Draw representation of a station tile for GUI purposes.
771 * @param x Position x of image.
772 * @param y Position y of image.
774 * @param railtype Rail type.
775 * @param sclass, station Type of station.
776 * @param station station ID
777 * @return True if the tile was drawn (allows for fallback to default graphic)
779 bool DrawStationTile(int x
, int y
, RailType railtype
, Axis axis
, StationClassID sclass
, uint station
)
781 const DrawTileSprites
*sprites
= nullptr;
782 const RailTypeInfo
*rti
= GetRailTypeInfo(railtype
);
783 PaletteID palette
= COMPANY_SPRITE_COLOUR(_local_company
);
786 const StationSpec
*statspec
= StationClass::Get(sclass
)->GetSpec(station
);
787 if (statspec
== nullptr) return false;
789 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
790 uint16_t callback
= GetStationCallback(CBID_STATION_SPRITE_LAYOUT
, 0, 0, statspec
, nullptr, INVALID_TILE
);
791 if (callback
!= CALLBACK_FAILED
) tile
= callback
& ~1;
794 uint32_t total_offset
= rti
->GetRailtypeSpriteOffset();
795 uint32_t relocation
= 0;
796 uint32_t ground_relocation
= 0;
797 const NewGRFSpriteLayout
*layout
= nullptr;
798 DrawTileSprites tmp_rail_layout
;
800 if (statspec
->renderdata
.empty()) {
801 sprites
= GetStationTileLayout(STATION_RAIL
, tile
+ axis
);
803 layout
= &statspec
->renderdata
[(tile
< statspec
->renderdata
.size()) ? tile
+ axis
: (uint
)axis
];
804 if (!layout
->NeedsPreprocessing()) {
810 if (layout
!= nullptr) {
811 /* Sprite layout which needs preprocessing */
812 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
813 uint32_t var10_values
= layout
->PrepareLayout(total_offset
, rti
->fallback_railtype
, 0, 0, separate_ground
);
814 for (uint8_t var10
: SetBitIterator(var10_values
)) {
815 uint32_t var10_relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, var10
);
816 layout
->ProcessRegisters(var10
, var10_relocation
, separate_ground
);
819 tmp_rail_layout
.seq
= layout
->GetLayout(&tmp_rail_layout
.ground
);
820 sprites
= &tmp_rail_layout
;
823 /* Simple sprite layout */
824 ground_relocation
= relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, 0);
825 if (HasBit(sprites
->ground
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) {
826 ground_relocation
= GetCustomStationRelocation(statspec
, nullptr, INVALID_TILE
, 1);
828 ground_relocation
+= rti
->fallback_railtype
;
831 SpriteID image
= sprites
->ground
.sprite
;
832 PaletteID pal
= sprites
->ground
.pal
;
833 RailTrackOffset overlay_offset
;
834 if (rti
->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &image
, &overlay_offset
)) {
835 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
836 DrawSprite(image
, PAL_NONE
, x
, y
);
837 DrawSprite(ground
+ overlay_offset
, PAL_NONE
, x
, y
);
839 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
840 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
841 DrawSprite(image
, GroundSpritePaletteTransform(image
, pal
, palette
), x
, y
);
844 DrawRailTileSeqInGUI(x
, y
, sprites
, total_offset
, relocation
, palette
);
850 const StationSpec
*GetStationSpec(TileIndex t
)
852 if (!IsCustomStationSpecIndex(t
)) return nullptr;
854 const BaseStation
*st
= BaseStation::GetByTile(t
);
855 uint specindex
= GetCustomStationSpecIndex(t
);
856 return specindex
< st
->speclist
.size() ? st
->speclist
[specindex
].spec
: nullptr;
859 /** Wrapper for animation control, see GetStationCallback. */
860 uint16_t GetAnimStationCallback(CallbackID callback
, uint32_t param1
, uint32_t param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, int)
862 return GetStationCallback(callback
, param1
, param2
, statspec
, st
, tile
);
865 /** Helper class for animation control. */
866 struct StationAnimationBase
: public AnimationBase
<StationAnimationBase
, StationSpec
, BaseStation
, int, GetAnimStationCallback
, TileAnimationFrameAnimationHelper
<BaseStation
> > {
867 static const CallbackID cb_animation_speed
= CBID_STATION_ANIMATION_SPEED
;
868 static const CallbackID cb_animation_next_frame
= CBID_STATION_ANIM_NEXT_FRAME
;
870 static const StationCallbackMask cbm_animation_speed
= CBM_STATION_ANIMATION_SPEED
;
871 static const StationCallbackMask cbm_animation_next_frame
= CBM_STATION_ANIMATION_NEXT_FRAME
;
874 void AnimateStationTile(TileIndex tile
)
876 const StationSpec
*ss
= GetStationSpec(tile
);
877 if (ss
== nullptr) return;
879 StationAnimationBase::AnimateTile(ss
, BaseStation::GetByTile(tile
), tile
, HasBit(ss
->flags
, SSF_CB141_RANDOM_BITS
));
882 void TriggerStationAnimation(BaseStation
*st
, TileIndex trigger_tile
, StationAnimationTrigger trigger
, CargoID cargo_type
)
884 /* List of coverage areas for each animation trigger */
885 static const TriggerArea tas
[] = {
886 TA_TILE
, TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_WHOLE
889 /* Get Station if it wasn't supplied */
890 if (st
== nullptr) st
= BaseStation::GetByTile(trigger_tile
);
892 /* Check the cached animation trigger bitmask to see if we need
893 * to bother with any further processing. */
894 if (!HasBit(st
->cached_anim_triggers
, trigger
)) return;
896 uint16_t random_bits
= Random();
897 ETileArea area
= ETileArea(st
, trigger_tile
, tas
[trigger
]);
899 /* Check all tiles over the station to check if the specindex is still in use */
900 for (TileIndex tile
: area
) {
901 if (st
->TileBelongsToRailStation(tile
)) {
902 const StationSpec
*ss
= GetStationSpec(tile
);
903 if (ss
!= nullptr && HasBit(ss
->animation
.triggers
, trigger
)) {
905 if (!IsValidCargoID(cargo_type
)) {
906 cargo
= INVALID_CARGO
;
908 cargo
= ss
->grf_prop
.grffile
->cargo_map
[cargo_type
];
910 StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIM_START_STOP
, ss
, st
, tile
, (random_bits
<< 16) | GB(Random(), 0, 16), (uint8_t)trigger
| (cargo
<< 8));
917 * Trigger station randomisation
918 * @param st station being triggered
919 * @param trigger_tile specific tile of platform to trigger
920 * @param trigger trigger type
921 * @param cargo_type cargo type causing trigger
923 void TriggerStationRandomisation(Station
*st
, TileIndex trigger_tile
, StationRandomTrigger trigger
, CargoID cargo_type
)
925 /* List of coverage areas for each animation trigger */
926 static const TriggerArea tas
[] = {
927 TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
930 /* Get Station if it wasn't supplied */
931 if (st
== nullptr) st
= Station::GetByTile(trigger_tile
);
933 /* Check the cached cargo trigger bitmask to see if we need
934 * to bother with any further processing. */
935 if (st
->cached_cargo_triggers
== 0) return;
936 if (IsValidCargoID(cargo_type
) && !HasBit(st
->cached_cargo_triggers
, cargo_type
)) return;
938 uint32_t whole_reseed
= 0;
939 ETileArea area
= ETileArea(st
, trigger_tile
, tas
[trigger
]);
941 /* Bitmask of completely empty cargo types to be matched. */
942 CargoTypes empty_mask
= (trigger
== SRT_CARGO_TAKEN
) ? GetEmptyMask(st
) : 0;
944 /* Store triggers now for var 5F */
945 SetBit(st
->waiting_triggers
, trigger
);
946 uint32_t used_triggers
= 0;
948 /* Check all tiles over the station to check if the specindex is still in use */
949 for (TileIndex tile
: area
) {
950 if (st
->TileBelongsToRailStation(tile
)) {
951 const StationSpec
*ss
= GetStationSpec(tile
);
952 if (ss
== nullptr) continue;
954 /* Cargo taken "will only be triggered if all of those
955 * cargo types have no more cargo waiting." */
956 if (trigger
== SRT_CARGO_TAKEN
) {
957 if ((ss
->cargo_triggers
& ~empty_mask
) != 0) continue;
960 if (!IsValidCargoID(cargo_type
) || HasBit(ss
->cargo_triggers
, cargo_type
)) {
961 StationResolverObject
object(ss
, st
, tile
, CBID_RANDOM_TRIGGER
, 0);
962 object
.waiting_triggers
= st
->waiting_triggers
;
964 const SpriteGroup
*group
= object
.Resolve();
965 if (group
== nullptr) continue;
967 used_triggers
|= object
.used_triggers
;
969 uint32_t reseed
= object
.GetReseedSum();
971 whole_reseed
|= reseed
;
974 /* Set individual tile random bits */
975 uint8_t random_bits
= GetStationTileRandomBits(tile
);
976 random_bits
&= ~reseed
;
977 random_bits
|= Random() & reseed
;
978 SetStationTileRandomBits(tile
, random_bits
);
980 MarkTileDirtyByTile(tile
);
986 /* Update whole station random bits */
987 st
->waiting_triggers
&= ~used_triggers
;
988 if ((whole_reseed
& 0xFFFF) != 0) {
989 st
->random_bits
&= ~whole_reseed
;
990 st
->random_bits
|= Random() & whole_reseed
;
995 * Update the cached animation trigger bitmask for a station.
996 * @param st Station to update.
998 void StationUpdateCachedTriggers(BaseStation
*st
)
1000 st
->cached_anim_triggers
= 0;
1001 st
->cached_cargo_triggers
= 0;
1003 /* Combine animation trigger bitmask for all station specs
1004 * of this station. */
1005 for (uint i
= 0; i
< st
->speclist
.size(); i
++) {
1006 const StationSpec
*ss
= st
->speclist
[i
].spec
;
1007 if (ss
!= nullptr) {
1008 st
->cached_anim_triggers
|= ss
->animation
.triggers
;
1009 st
->cached_cargo_triggers
|= ss
->cargo_triggers
;