4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file newgrf_station.cpp Functions for dealing with station classes and custom stations. */
14 #include "station_base.h"
15 #include "waypoint_base.h"
16 #include "roadstop_base.h"
17 #include "newgrf_cargo.h"
18 #include "newgrf_station.h"
19 #include "newgrf_spritegroup.h"
20 #include "newgrf_sound.h"
21 #include "newgrf_railtype.h"
23 #include "newgrf_town.h"
24 #include "company_func.h"
25 #include "map/slope.h"
26 #include "newgrf_animation_base.h"
27 #include "newgrf_class_func.h"
29 #include "station_func.h"
33 /* static */ void NewGRFClass
<StationSpec
, StationClassID
, STAT_CLASS_MAX
>::InsertDefaults()
35 /* Set up initial data */
36 classes
[0].global_id
= 'DFLT';
37 classes
[0].name
= STR_STATION_CLASS_DFLT
;
38 classes
[0].Insert(NULL
);
40 classes
[1].global_id
= 'WAYP';
41 classes
[1].name
= STR_STATION_CLASS_WAYP
;
42 classes
[1].Insert(NULL
);
46 bool NewGRFClass
<StationSpec
, StationClassID
, STAT_CLASS_MAX
>::IsUIAvailable (uint index
) const
51 INSTANTIATE_NEWGRF_CLASS_METHODS(StationClass
)
53 static const uint NUM_STATIONSSPECS_PER_STATION
= 255; ///< Maximum number of parts per station.
61 struct ETileArea
: TileArea
{
62 ETileArea(const BaseStation
*st
, TileIndex tile
, TriggerArea ta
)
65 default: NOT_REACHED();
75 Axis axis
= GetRailStationAxis(tile
);
76 TileIndexDiff delta
= TileOffsByDiagDir(AxisToDiagDir(axis
));
78 for (end
= tile
; IsRailStationTile(end
+ delta
) && IsCompatibleTrainStationTile(end
+ delta
, tile
); end
+= delta
) { /* Nothing */ }
79 for (start
= tile
; IsRailStationTile(start
- delta
) && IsCompatibleTrainStationTile(start
- delta
, tile
); start
-= delta
) { /* Nothing */ }
82 this->w
= TileX(end
) - TileX(start
) + 1;
83 this->h
= TileY(end
) - TileY(start
) + 1;
88 st
->GetTileArea(this, st
->IsWaypoint() ? STATION_WAYPOINT
: STATION_RAIL
);
96 * Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
97 * if not centered: .TNLcCpP, if centered: .TNL..CP
98 * - T = Tile layout number (#GetStationGfx)
99 * - N = Number of platforms
100 * - L = Length of platforms
101 * - C = Current platform number from start, c = from end
102 * - P = Position along platform from start, p = from end
104 * if centered, C/P start from the centre and c/p are not available.
105 * @return Platform information in bit-stuffed format.
107 uint32
GetPlatformInfo(Axis axis
, byte tile
, int platforms
, int length
, int x
, int y
, bool centred
)
111 if (axis
== AXIS_X
) {
112 Swap(platforms
, length
);
121 SB(retval
, 0, 4, y
& 0xF);
122 SB(retval
, 4, 4, x
& 0xF);
124 SB(retval
, 0, 4, min(15, y
));
125 SB(retval
, 4, 4, min(15, length
- y
- 1));
126 SB(retval
, 8, 4, min(15, x
));
127 SB(retval
, 12, 4, min(15, platforms
- x
- 1));
129 SB(retval
, 16, 4, min(15, length
));
130 SB(retval
, 20, 4, min(15, platforms
));
131 SB(retval
, 24, 4, tile
);
138 * Find the end of a railway station, from the \a tile, in the direction of \a delta.
139 * @param tile Start tile.
140 * @param delta Movement direction.
141 * @param check_type Stop when the custom station type changes.
142 * @param check_axis Stop when the station direction changes.
143 * @return Found end of the railway station.
145 static TileIndex
FindRailStationEnd(TileIndex tile
, TileIndexDiff delta
, bool check_type
, bool check_axis
)
148 Axis orig_axis
= AXIS_X
;
149 StationID sid
= GetStationIndex(tile
);
151 if (check_type
) orig_type
= GetCustomStationSpecIndex(tile
);
152 if (check_axis
) orig_axis
= GetRailStationAxis(tile
);
155 TileIndex new_tile
= TILE_ADD(tile
, delta
);
157 if (!IsStationTile(new_tile
) || GetStationIndex(new_tile
) != sid
) break;
158 if (!HasStationRail(new_tile
)) break;
159 if (check_type
&& GetCustomStationSpecIndex(new_tile
) != orig_type
) break;
160 if (check_axis
&& GetRailStationAxis(new_tile
) != orig_axis
) break;
168 static uint32
GetPlatformInfoHelper(TileIndex tile
, bool check_type
, bool check_axis
, bool centred
)
170 int tx
= TileX(tile
);
171 int ty
= TileY(tile
);
172 int sx
= TileX(FindRailStationEnd(tile
, TileDiffXY(-1, 0), check_type
, check_axis
));
173 int sy
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, -1), check_type
, check_axis
));
174 int ex
= TileX(FindRailStationEnd(tile
, TileDiffXY( 1, 0), check_type
, check_axis
)) + 1;
175 int ey
= TileY(FindRailStationEnd(tile
, TileDiffXY( 0, 1), check_type
, check_axis
)) + 1;
180 return GetPlatformInfo(GetRailStationAxis(tile
), GetStationGfx(tile
), ex
, ey
, tx
, ty
, centred
);
184 static uint32
GetRailContinuationInfo(TileIndex tile
)
191 /* Tile offsets and exit dirs for X axis */
192 static const DataPair data_x
[8] = {
193 { DIR_SW
, DIAGDIR_SW
},
194 { DIR_NE
, DIAGDIR_NE
},
195 { DIR_SE
, DIAGDIR_SE
},
196 { DIR_NW
, DIAGDIR_NW
},
197 { DIR_S
, DIAGDIR_SW
},
198 { DIR_E
, DIAGDIR_NE
},
199 { DIR_W
, DIAGDIR_SW
},
200 { DIR_N
, DIAGDIR_NE
},
203 /* Tile offsets and exit dirs for Y axis */
204 static const DataPair data_y
[8] = {
205 { DIR_SE
, DIAGDIR_SE
},
206 { DIR_NW
, DIAGDIR_NW
},
207 { DIR_SW
, DIAGDIR_SW
},
208 { DIR_NE
, DIAGDIR_NE
},
209 { DIR_S
, DIAGDIR_SE
},
210 { DIR_W
, DIAGDIR_NW
},
211 { DIR_E
, DIAGDIR_SE
},
212 { DIR_N
, DIAGDIR_NW
},
215 Axis axis
= GetRailStationAxis(tile
);
217 /* Choose appropriate lookup table to use */
218 const DataPair
*data
= (axis
== AXIS_X
) ? data_x
: data_y
;
221 for (uint i
= 0; i
< lengthof(data_x
); i
++, data
++) {
222 TileIndex neighbour_tile
= tile
+ TileOffsByDir (data
->dir
);
223 TrackBits trackbits
= TrackStatusToTrackBits(GetTileRailwayStatus(neighbour_tile
));
224 if (trackbits
!= TRACK_BIT_NONE
) {
225 /* If there is any track on the tile, set the bit in the second byte */
228 /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
229 * with the next tile because the ramp is not going in the right direction. */
230 if (IsTunnelTile (neighbour_tile
)) {
231 if (GetTunnelBridgeDirection (neighbour_tile
) != data
->exit
) {
234 } else if (IsBridgeHeadTile (neighbour_tile
)) {
235 if (GetTunnelBridgeDirection (neighbour_tile
) == ReverseDiagDir (data
->exit
)) {
240 /* If any track reaches our exit direction, set the bit in the lower byte */
241 if (trackbits
& DiagdirReachesTracks(data
->exit
)) SetBit(res
, i
);
249 /* Station Resolver Functions */
250 /* virtual */ uint32
StationScopeResolver::GetRandomBits() const
252 return this->st
->random_bits
| (this->tile
== INVALID_TILE
? 0 : GetStationTileRandomBits (this->tile
) << 16);
256 /* virtual */ uint32
StationScopeResolver::GetTriggers() const
258 return this->st
->waiting_triggers
;
262 /* virtual */ void StationScopeResolver::SetTriggers(int triggers
) const
264 BaseStation
*st
= const_cast<BaseStation
*>(this->st
);
266 st
->waiting_triggers
= triggers
;
270 * Station variable cache
271 * This caches 'expensive' station variable lookups which iterate over
272 * several tiles that may be called multiple times per Resolve().
281 uint8 valid
; ///< Bits indicating what variable is valid (for each bit, \c 0 is invalid, \c 1 is valid).
285 * Get the town scope associated with a station, if it exists.
286 * On the first call, the town scope is created (if possible).
287 * @return Town scope, if available.
289 TownScopeResolver
*StationResolverObject::GetTown()
291 if (this->town_scope
== NULL
) {
292 Town
*t
= this->station_scope
.st
->town
;
293 if (t
== NULL
) return NULL
;
294 this->town_scope
= new TownScopeResolver (this->grffile
, t
, false);
296 return this->town_scope
;
299 /* virtual */ uint32
StationScopeResolver::GetVariable(byte variable
, uint32 parameter
, bool *available
) const
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->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 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 res
= GB(GetStationGfx(nearby_tile
), 1, 2) << 12 | !!perpendicular
<< 11 | !!same_station
<< 10;
362 uint spec_index
= GetCustomStationSpecIndex (nearby_tile
);
363 if (spec_index
!= 0) {
364 const StationSpecList ssl
= BaseStation::GetByTile(nearby_tile
)->speclist
[spec_index
];
365 res
|= 1 << (ssl
.grfid
!= grfid
? 9 : 8) | ssl
.localidx
;
370 /* General station variables */
371 case 0x82: return 50;
372 case 0x84: return this->st
->string_id
;
374 case 0xF0: return this->st
->facilities
;
375 case 0xFA: return Clamp(this->st
->build_date
- DAYS_TILL_ORIGINAL_BASE_YEAR
, 0, 65535);
378 return this->st
->GetNewGRFVariable (this->grffile
, variable
, parameter
, available
);
381 uint32
Station::GetNewGRFVariable (const GRFFile
*grffile
, byte variable
, byte parameter
, bool *available
) const
384 case 0x48: { // Accepted cargo types
388 for (cargo_type
= 0; cargo_type
< NUM_CARGO
; cargo_type
++) {
389 if (HasBit(this->goods
[cargo_type
].status
, GoodsEntry::GES_ACCEPTANCE
)) SetBit(value
, cargo_type
);
394 case 0x8A: return this->had_vehicle_of_type
;
395 case 0xF1: return (this->airport
.tile
!= INVALID_TILE
) ? this->airport
.GetSpec()->ttd_airport_type
: ATP_TTDP_LARGE
;
396 case 0xF2: return (this->truck_stops
!= NULL
) ? this->truck_stops
->status
: 0;
397 case 0xF3: return (this->bus_stops
!= NULL
) ? this->bus_stops
->status
: 0;
398 case 0xF6: return this->airport
.flags
;
399 case 0xF7: return GB(this->airport
.flags
, 8, 8);
402 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
403 if ((variable
>= 0x60 && variable
<= 0x65) || variable
== 0x69) {
404 CargoID c
= GetCargoTranslation (parameter
, grffile
);
406 if (c
== CT_INVALID
) {
408 case 0x62: return 0xFFFFFFFF;
409 case 0x64: return 0xFF00;
413 const GoodsEntry
*ge
= &this->goods
[c
];
416 case 0x60: return min(ge
->cargo
.TotalCount(), 4095);
417 case 0x61: return ge
->HasVehicleEverTriedLoading() ? ge
->time_since_pickup
: 0;
418 case 0x62: return ge
->HasRating() ? ge
->rating
: 0xFFFFFFFF;
419 case 0x63: return ge
->cargo
.DaysInTransit();
420 case 0x64: return ge
->HasVehicleEverTriedLoading() ? ge
->last_speed
| (ge
->last_age
<< 8) : 0xFF00;
421 case 0x65: return GB(ge
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 3;
423 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED
+ 1 == (int)GoodsEntry::GES_LAST_MONTH
);
424 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED
+ 2 == (int)GoodsEntry::GES_CURRENT_MONTH
);
425 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED
+ 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK
);
426 return GB(ge
->status
, GoodsEntry::GES_EVER_ACCEPTED
, 4);
431 /* Handle cargo variables (deprecated) */
432 if (variable
>= 0x8C && variable
<= 0xEC) {
433 const GoodsEntry
*g
= &this->goods
[GB(variable
- 0x8C, 3, 4)];
434 switch (GB(variable
- 0x8C, 0, 3)) {
435 case 0: return g
->cargo
.TotalCount();
436 case 1: return GB(min(g
->cargo
.TotalCount(), 4095), 0, 4) | (GB(g
->status
, GoodsEntry::GES_ACCEPTANCE
, 1) << 7);
437 case 2: return g
->time_since_pickup
;
438 case 3: return g
->rating
;
439 case 4: return g
->cargo
.Source();
440 case 5: return g
->cargo
.DaysInTransit();
441 case 6: return g
->last_speed
;
442 case 7: return g
->last_age
;
446 DEBUG(grf
, 1, "Unhandled station variable 0x%X", variable
);
452 uint32
Waypoint::GetNewGRFVariable (const GRFFile
*grffile
, byte variable
, byte parameter
, bool *available
) const
455 case 0x48: return 0; // Accepted cargo types
456 case 0x8A: return HVOT_WAYPOINT
;
457 case 0xF1: return 0; // airport type
458 case 0xF2: return 0; // truck stop status
459 case 0xF3: return 0; // bus stop status
460 case 0xF6: return 0; // airport flags
461 case 0xF7: return 0; // airport flags cont.
464 /* Handle cargo variables with parameter, 0x60 to 0x65 */
465 if (variable
>= 0x60 && variable
<= 0x65) {
469 /* Handle cargo variables (deprecated) */
470 if (variable
>= 0x8C && variable
<= 0xEC) {
471 switch (GB(variable
- 0x8C, 0, 3)) {
472 case 3: return INITIAL_STATION_RATING
;
473 case 4: return INVALID_STATION
;
478 DEBUG(grf
, 1, "Unhandled station variable 0x%X", variable
);
484 /* virtual */ const SpriteGroup
*StationResolverObject::ResolveReal(const RealSpriteGroup
*group
) const
486 if (this->station_scope
.statspec
->cls_id
== STAT_CLASS_WAYP
) {
487 return group
->get_first (true);
491 const Station
*st
= Station::From(this->station_scope
.st
);
493 switch (this->station_scope
.cargo_type
) {
501 for (CargoID cargo_type
= 0; cargo_type
< NUM_CARGO
; cargo_type
++) {
502 cargo
+= st
->goods
[cargo_type
].cargo
.TotalCount();
507 cargo
= st
->goods
[this->station_scope
.cargo_type
].cargo
.TotalCount();
511 if (HasBit(this->station_scope
.statspec
->flags
, SSF_DIV_BY_STATION_SIZE
)) cargo
/= (st
->train_station
.w
+ st
->train_station
.h
);
512 cargo
= min(0xfff, cargo
);
514 uint threshold
= this->station_scope
.statspec
->cargo_threshold
;
515 if (cargo
> threshold
) {
516 uint count
= group
->get_count (true);
518 uint set
= ((cargo
- threshold
) * count
) / (4096 - threshold
);
519 return group
->get_group (true, set
);
522 uint count
= group
->get_count (false);
524 uint set
= (cargo
* count
) / (threshold
+ 1);
525 return group
->get_group (false, set
);
529 return group
->get_first (false);
533 * Resolver for stations.
534 * @param statspec Station (type) specification.
535 * @param st Instance of the station.
536 * @param tile %Tile of the station.
537 * @param callback Callback ID.
538 * @param callback_param1 First parameter (var 10) of the callback.
539 * @param callback_param2 Second parameter (var 18) of the callback.
541 StationResolverObject::StationResolverObject(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
,
542 CallbackID callback
, uint32 callback_param1
, uint32 callback_param2
)
543 : ResolverObject(statspec
->grf_prop
.grffile
, callback
, callback_param1
, callback_param2
),
544 station_scope (this->grffile
, statspec
, st
, tile
), town_scope(NULL
)
548 /* Invalidate all cached vars */
551 CargoID ctype
= CT_DEFAULT_NA
;
553 if (!this->station_scope
.st
->IsWaypoint()) {
554 const Station
*st
= Station::From(this->station_scope
.st
);
555 /* Pick the first cargo that we have waiting */
557 FOR_ALL_CARGOSPECS(cs
) {
558 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[cs
->Index()] != NULL
&&
559 st
->goods
[cs
->Index()].cargo
.TotalCount() > 0) {
566 if (this->station_scope
.statspec
->grf_prop
.spritegroup
[ctype
] == NULL
) {
570 /* Remember the cargo type we've picked */
571 this->station_scope
.cargo_type
= ctype
;
572 this->root_spritegroup
= this->station_scope
.statspec
->grf_prop
.spritegroup
[this->station_scope
.cargo_type
];
575 StationResolverObject::~StationResolverObject()
577 delete this->town_scope
;
581 * Constructor for station scopes.
582 * @param grffile GRFFile the resolved SpriteGroup belongs to.
583 * @param statspec Station (type) specification.
584 * @param st Instance of the station.
585 * @param tile %Tile of the station.
587 StationScopeResolver::StationScopeResolver (const GRFFile
*grffile
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
)
588 : ScopeResolver(), grffile(grffile
)
594 this->statspec
= statspec
;
595 this->cargo_type
= CT_INVALID
;
599 /** Scope resolver for stations not yet built. */
600 struct FakeStationScopeResolver
: public ScopeResolver
{
601 const GRFFile
*const grffile
; ///< GRFFile the resolved SpriteGroup belongs to.
602 TileIndex tile
; ///< %Tile of the station.
603 const struct StationSpec
*statspec
; ///< Station (type) specification.
604 RailType railtype
; ///< Rail type.
605 Axis axis
; ///< Station axis, used only for the slope check callback.
607 FakeStationScopeResolver (const GRFFile
*grffile
, const StationSpec
*statspec
,
608 TileIndex tile
, RailType rt
, Axis axis
= INVALID_AXIS
)
609 : ScopeResolver(), grffile(grffile
), tile(tile
),
610 statspec(statspec
), railtype(rt
), axis(axis
)
614 uint32
GetVariable (byte variable
, uint32 parameter
, bool *available
) const OVERRIDE
;
617 uint32
FakeStationScopeResolver::GetVariable (byte variable
, uint32 parameter
, bool *available
) const
619 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
625 case 0x49: return 0x2110000; // Platforms, tracks & position
626 case 0x42: return GetReverseRailTypeTranslation (this->railtype
, this->statspec
->grf_prop
.grffile
) << 8;
627 case 0x43: return GetCompanyInfo (_current_company
); // Station owner
628 case 0x44: return 2; // PBS status
629 case 0x67: // Land info of nearby tile
630 if (this->axis
!= INVALID_AXIS
&& this->tile
!= INVALID_TILE
) {
631 TileIndex tile
= this->tile
;
632 if (parameter
!= 0) tile
= GetNearbyTile (parameter
, tile
, true, this->axis
); // only perform if it is required
634 Slope tileh
= GetTileSlope(tile
);
635 bool swap
= (this->axis
== AXIS_Y
&& HasBit(tileh
, CORNER_W
) != HasBit(tileh
, CORNER_E
));
637 return GetNearbyTileInformation (tile
, this->grffile
->grf_version
>= 8) ^ (swap
? SLOPE_EW
: 0);
641 case 0xFA: return Clamp (_date
- DAYS_TILL_ORIGINAL_BASE_YEAR
, 0, 65535); // Build date, clamped to a 16 bit value
648 /** Resolver for stations not yet built. */
649 struct FakeStationResolverObject
: public ResolverObject
{
650 FakeStationScopeResolver station_scope
; ///< The station scope resolver.
651 TownScopeResolver
*town_scope
; ///< The town scope resolver (created on the first call).
653 const SpriteGroup
*root_spritegroup
; ///< Root SpriteGroup to use for resolving
656 * Resolver for stations not yet built.
657 * @param statspec Station (type) specification.
658 * @param tile %Tile of the station.
659 * @param rt Rail type.
660 * @param callback Callback ID.
661 * @param callback_param1 First parameter (var 10) of the callback.
662 * @param callback_param2 Second parameter (var 18) of the callback.
663 * @param axis Axis of the station tile to build, if any.
665 FakeStationResolverObject (const StationSpec
*statspec
, TileIndex tile
,
666 RailType rt
, CallbackID callback
= CBID_NO_CALLBACK
,
667 uint32 callback_param1
= 0, uint32 callback_param2
= 0,
668 Axis axis
= INVALID_AXIS
)
669 : ResolverObject (statspec
->grf_prop
.grffile
,
670 callback
, callback_param1
, callback_param2
),
671 station_scope (this->grffile
, statspec
, tile
, rt
, axis
),
674 /* Invalidate all cached vars */
677 /* No station, so we are in a purchase list */
678 const SpriteGroup
*const *groups
= statspec
->grf_prop
.spritegroup
;
679 const SpriteGroup
*root
= groups
[CT_PURCHASE
];
682 root
= groups
[CT_DEFAULT
];
685 this->root_spritegroup
= root
;
688 ~FakeStationResolverObject();
690 TownScopeResolver
*GetTown (void);
692 ScopeResolver
*GetScope (VarSpriteGroupScope scope
= VSG_SCOPE_SELF
, byte relative
= 0) OVERRIDE
696 return &this->station_scope
;
698 case VSG_SCOPE_PARENT
: {
699 TownScopeResolver
*tsr
= this->GetTown();
700 if (tsr
!= NULL
) return tsr
;
705 return ResolverObject::GetScope (scope
, relative
);
709 const SpriteGroup
*ResolveReal (const RealSpriteGroup
*group
) const OVERRIDE
711 return group
->get_first (true);
715 * Resolve SpriteGroup.
716 * @return Result spritegroup.
718 const SpriteGroup
*Resolve (void)
720 return SpriteGroup::Resolve (this->root_spritegroup
, *this);
724 FakeStationResolverObject::~FakeStationResolverObject()
726 delete this->town_scope
;
730 * Get the town scope associated with a station, if it exists.
731 * On the first call, the town scope is created (if possible).
732 * @return Town scope, if available.
734 TownScopeResolver
*FakeStationResolverObject::GetTown (void)
736 if (this->town_scope
== NULL
) {
738 if (this->station_scope
.tile
!= INVALID_TILE
) {
739 t
= ClosestTownFromTile(this->station_scope
.tile
);
741 if (t
== NULL
) return NULL
;
742 this->town_scope
= new TownScopeResolver (this->grffile
, t
, true);
744 return this->town_scope
;
749 * Resolve sprites for drawing a station tile.
750 * @param statspec Station spec
752 * @param tile Station tile being drawn
753 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
754 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
756 SpriteID
GetCustomStationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint32 var10
)
759 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, var10
);
760 const SpriteGroup
*group
= object
.Resolve();
761 if (group
== NULL
|| !group
->IsType (SGT_RESULT
)) return 0;
762 return group
->GetResult() - 0x42D;
766 * Resolve sprites for drawing a station tile in the GUI.
767 * @param statspec Station spec
768 * @param rt Rail type.
769 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
770 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
772 static SpriteID
GetCustomStationRelocation (const StationSpec
*statspec
,
773 RailType rt
, uint32 var10
)
775 FakeStationResolverObject
object (statspec
, INVALID_TILE
, rt
, CBID_NO_CALLBACK
, var10
);
776 const SpriteGroup
*group
= object
.Resolve();
777 if (group
== NULL
|| !group
->IsType (SGT_RESULT
)) return 0;
778 return group
->GetResult() - 0x42D;
782 * Resolve the sprites for custom station foundations.
783 * @param statspec Station spec
785 * @param tile Station tile being drawn
786 * @param layout Spritelayout as returned by previous callback
787 * @param edge_info Information about northern tile edges; whether they need foundations or merge into adjacent tile's foundations.
788 * @return First sprite of a set of foundation sprites for various slopes, or 0 if default foundations shall be drawn.
790 SpriteID
GetCustomStationFoundationRelocation(const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
, uint layout
, uint edge_info
)
792 /* callback_param1 == 2 means we are resolving the foundation sprites. */
793 StationResolverObject
object(statspec
, st
, tile
, CBID_NO_CALLBACK
, 2, layout
| (edge_info
<< 16));
795 const SpriteGroup
*group
= object
.Resolve();
796 if (group
== NULL
|| !group
->IsType (SGT_RESULT
)) return 0;
798 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
799 return group
->GetResult() + GetRegister(0x100);
803 uint16
GetStationCallback(CallbackID callback
, uint32 param1
, uint32 param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
)
806 StationResolverObject
object(statspec
, st
, tile
, callback
, param1
, param2
);
807 return SpriteGroup::CallbackResult (object
.Resolve());
810 uint16
GetStationCallback (CallbackID callback
, uint32 param1
, uint32 param2
,
811 const StationSpec
*statspec
, RailType rt
, TileIndex tile
)
813 FakeStationResolverObject
object (statspec
, tile
, rt
, callback
, param1
, param2
);
814 return SpriteGroup::CallbackResult (object
.Resolve());
818 * Check the slope of a tile of a new station.
819 * @param north_tile Norther tile of the station rect.
820 * @param cur_tile Tile to check.
821 * @param statspec Station spec.
822 * @param rt Rail type.
823 * @param axis Axis of the new station.
824 * @param plat_len Platform length.
825 * @param numtracks Number of platforms.
826 * @return Succeeded or failed command.
828 CommandCost
PerformStationTileSlopeCheck (TileIndex north_tile
,
829 TileIndex cur_tile
, const StationSpec
*statspec
, RailType rt
,
830 Axis axis
, byte plat_len
, byte numtracks
)
832 TileIndexDiff diff
= cur_tile
- north_tile
;
833 Slope slope
= GetTileSlope(cur_tile
);
835 FakeStationResolverObject
object (statspec
, cur_tile
, rt
, CBID_STATION_LAND_SLOPE_CHECK
,
836 (slope
<< 4) | (slope
^ (axis
== AXIS_Y
&& HasBit(slope
, CORNER_W
) != HasBit(slope
, CORNER_E
) ? SLOPE_EW
: 0)),
837 (numtracks
<< 24) | (plat_len
<< 16) | (axis
== AXIS_Y
? TileX(diff
) << 8 | TileY(diff
) : TileY(diff
) << 8 | TileX(diff
)),
840 uint16 cb_res
= SpriteGroup::CallbackResult (object
.Resolve());
842 /* Failed callback means success. */
843 if (cb_res
== CALLBACK_FAILED
) return CommandCost();
845 /* The meaning of bit 10 is inverted for a grf version < 8. */
846 if (statspec
->grf_prop
.grffile
->grf_version
< 8) ToggleBit(cb_res
, 10);
847 return GetErrorMessageFromLocationCallbackResult(cb_res
, statspec
->grf_prop
.grffile
, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION
);
852 * Allocate a StationSpec to a Station. This is called once per build operation.
853 * @param statspec StationSpec to allocate.
854 * @param st Station to allocate it to.
855 * @param exec Whether to actually allocate the spec.
856 * @return Index within the Station's spec list, or -1 if the allocation failed.
858 int AllocateSpecToStation(const StationSpec
*statspec
, BaseStation
*st
, bool exec
)
862 if (statspec
== NULL
|| st
== NULL
) return 0;
864 for (i
= 1; i
< st
->num_specs
&& i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
865 if (st
->speclist
[i
].spec
== NULL
&& st
->speclist
[i
].grfid
== 0) break;
868 if (i
== NUM_STATIONSSPECS_PER_STATION
) {
869 /* As final effort when the spec list is already full...
870 * try to find the same spec and return that one. This might
871 * result in slightly "wrong" (as per specs) looking stations,
872 * but it's fairly unlikely that one reaches the limit anyways.
874 for (i
= 1; i
< st
->num_specs
&& i
< NUM_STATIONSSPECS_PER_STATION
; i
++) {
875 if (st
->speclist
[i
].spec
== statspec
) return i
;
882 if (i
>= st
->num_specs
) {
883 st
->num_specs
= i
+ 1;
884 st
->speclist
= xrealloct (st
->speclist
, st
->num_specs
);
886 if (st
->num_specs
== 2) {
887 /* Initial allocation */
888 st
->speclist
[0].spec
= NULL
;
889 st
->speclist
[0].grfid
= 0;
890 st
->speclist
[0].localidx
= 0;
894 st
->speclist
[i
].spec
= statspec
;
895 st
->speclist
[i
].grfid
= statspec
->grf_prop
.grffile
->grfid
;
896 st
->speclist
[i
].localidx
= statspec
->grf_prop
.local_id
;
898 StationUpdateCachedTriggers(st
);
906 * Deallocate a StationSpec from a Station. Called when removing a single station tile.
907 * @param st Station to work with.
908 * @param specindex Index of the custom station within the Station's spec list.
909 * @return Indicates whether the StationSpec was deallocated.
911 void DeallocateSpecFromStation(BaseStation
*st
, byte specindex
)
913 /* specindex of 0 (default) is never freeable */
914 if (specindex
== 0) return;
916 ETileArea area
= ETileArea(st
, INVALID_TILE
, TA_WHOLE
);
917 /* Check all tiles over the station to check if the specindex is still in use */
918 TILE_AREA_LOOP(tile
, area
) {
919 if (st
->TileBelongsToRailStation(tile
) && GetCustomStationSpecIndex(tile
) == specindex
) {
924 /* This specindex is no longer in use, so deallocate it */
925 st
->speclist
[specindex
].spec
= NULL
;
926 st
->speclist
[specindex
].grfid
= 0;
927 st
->speclist
[specindex
].localidx
= 0;
929 /* If this was the highest spec index, reallocate */
930 if (specindex
== st
->num_specs
- 1) {
931 for (; st
->speclist
[st
->num_specs
- 1].grfid
== 0 && st
->num_specs
> 1; st
->num_specs
--) {}
933 if (st
->num_specs
> 1) {
934 st
->speclist
= xrealloct (st
->speclist
, st
->num_specs
);
939 st
->cached_anim_triggers
= 0;
940 st
->cached_cargo_triggers
= 0;
945 StationUpdateCachedTriggers(st
);
949 * Draw representation of a station tile for GUI purposes.
950 * @param dpi The area to draw on.
951 * @param x Position x of image.
952 * @param y Position y of image.
954 * @param railtype Rail type.
955 * @param sclass, station Type of station.
956 * @param station station ID
957 * @return True if the tile was drawn (allows for fallback to default graphic)
959 bool DrawStationTile (BlitArea
*dpi
, int x
, int y
, RailType railtype
,
960 Axis axis
, StationClassID sclass
, uint station
)
962 const DrawTileSprites
*sprites
= NULL
;
963 const RailtypeInfo
*rti
= GetRailTypeInfo(railtype
);
964 PaletteID palette
= COMPANY_SPRITE_COLOUR(_local_company
);
967 const StationSpec
*statspec
= StationClass::Get(sclass
)->GetSpec(station
);
968 if (statspec
== NULL
) return false;
970 if (HasBit(statspec
->callback_mask
, CBM_STATION_SPRITE_LAYOUT
)) {
971 uint16 callback
= GetStationCallback (CBID_STATION_SPRITE_LAYOUT
, 0x2110000, 0, statspec
, railtype
);
972 if (callback
!= CALLBACK_FAILED
) tile
= callback
;
975 uint32 total_offset
= rti
->GetRailtypeSpriteOffset();
976 uint32 relocation
= 0;
977 uint32 ground_relocation
= 0;
978 const NewGRFSpriteLayout
*layout
= NULL
;
980 if (statspec
->renderdata
.empty()) {
981 sprites
= GetDefaultStationTileLayout() + (tile
+ axis
);
983 uint t
= (tile
< statspec
->renderdata
.size()) ? tile
: 0;
984 layout
= statspec
->renderdata
[t
+ axis
].get();
985 if (!layout
->NeedsPreprocessing()) {
991 NewGRFSpriteLayout::Result result
;
993 const DrawTileSeqStruct
*seq
;
994 if (layout
!= NULL
) {
995 /* Sprite layout which needs preprocessing */
996 bool separate_ground
= HasBit(statspec
->flags
, SSF_SEPARATE_GROUND
);
997 uint32 var10_values
= result
.prepare (layout
, 0, total_offset
, rti
->fallback_railtype
, separate_ground
);
999 FOR_EACH_SET_BIT(var10
, var10_values
) {
1000 uint32 var10_relocation
= GetCustomStationRelocation (statspec
, railtype
, var10
);
1001 result
.process (layout
, var10
, var10_relocation
, separate_ground
);
1003 ground
= result
.get_ground();
1004 seq
= result
.get_seq();
1007 /* Simple sprite layout */
1008 ground
= sprites
->ground
;
1010 ground_relocation
= relocation
= GetCustomStationRelocation (statspec
, railtype
, 0);
1011 if (HasBit(ground
.sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) {
1012 ground_relocation
= GetCustomStationRelocation (statspec
, railtype
, 1);
1014 ground_relocation
+= rti
->fallback_railtype
;
1017 SpriteID image
= ground
.sprite
;
1018 PaletteID pal
= ground
.pal
;
1019 RailTrackOffset overlay_offset
;
1020 if (rti
->UsesOverlay() && SplitGroundSpriteForOverlay (&image
, &overlay_offset
)) {
1021 SpriteID ground
= GetCustomRailSprite(rti
, INVALID_TILE
, RTSG_GROUND
);
1022 DrawSprite (dpi
, image
, PAL_NONE
, x
, y
);
1023 DrawSprite (dpi
, ground
+ overlay_offset
, PAL_NONE
, x
, y
);
1025 image
+= HasBit(image
, SPRITE_MODIFIER_CUSTOM_SPRITE
) ? ground_relocation
: total_offset
;
1026 if (HasBit(pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
)) pal
+= ground_relocation
;
1027 DrawSprite (dpi
, image
, GroundSpritePaletteTransform (image
, pal
, palette
), x
, y
);
1030 DrawRailTileSeqInGUI (dpi
, x
, y
, seq
, total_offset
, relocation
, palette
);
1036 const StationSpec
*GetStationSpec(TileIndex t
)
1038 uint specindex
= GetCustomStationSpecIndex(t
);
1039 if (specindex
== 0) return NULL
;
1041 const BaseStation
*st
= BaseStation::GetByTile(t
);
1042 return specindex
< st
->num_specs
? st
->speclist
[specindex
].spec
: NULL
;
1047 * Check whether a rail station tile is NOT traversable.
1048 * @param tile %Tile to test.
1049 * @return Station tile is blocked.
1050 * @note This could be cached (during build) in the map array to save on all the dereferencing.
1052 bool IsStationTileBlocked(TileIndex tile
)
1054 const StationSpec
*statspec
= GetStationSpec(tile
);
1056 return statspec
!= NULL
&& HasBit(statspec
->blocked
, GetStationGfx(tile
));
1060 * Check if a rail station tile shall have pylons when electrified.
1061 * @param tile %Tile to test.
1062 * @return Tile shall have pylons.
1063 * @note This could be cached (during build) in the map array to save on all the dereferencing.
1065 bool CanStationTileHavePylons(TileIndex tile
)
1067 const StationSpec
*statspec
= GetStationSpec(tile
);
1068 uint gfx
= GetStationGfx(tile
);
1069 /* Default stations do not draw pylons under roofs (gfx >= 4) */
1070 return statspec
!= NULL
? HasBit(statspec
->pylons
, gfx
) : gfx
< 4;
1074 * Check if a rail station tile shall have wires when electrified.
1075 * @param tile %Tile to test.
1076 * @return Tile shall have wires.
1077 * @note This could be cached (during build) in the map array to save on all the dereferencing.
1079 bool CanStationTileHaveWires(TileIndex tile
)
1081 const StationSpec
*statspec
= GetStationSpec(tile
);
1082 return statspec
== NULL
|| !HasBit(statspec
->wires
, GetStationGfx(tile
));
1085 /** Helper class for animation control. */
1086 struct StationAnimationBase
{
1087 static const CallbackID cb_animation_speed
= CBID_STATION_ANIMATION_SPEED
;
1088 static const CallbackID cb_animation_next_frame
= CBID_STATION_ANIM_NEXT_FRAME
;
1090 static const StationCallbackMask cbm_animation_speed
= CBM_STATION_ANIMATION_SPEED
;
1091 static const StationCallbackMask cbm_animation_next_frame
= CBM_STATION_ANIMATION_NEXT_FRAME
;
1093 /** Callback wrapper for animation control. */
1094 static uint16
get_callback (CallbackID callback
, uint32 param1
, uint32 param2
, const StationSpec
*statspec
, BaseStation
*st
, TileIndex tile
)
1096 return GetStationCallback (callback
, param1
, param2
, statspec
, st
, tile
);
1100 void AnimateStationTile(TileIndex tile
)
1102 const StationSpec
*ss
= GetStationSpec(tile
);
1103 if (ss
== NULL
) return;
1105 AnimationBase::AnimateTile
<StationAnimationBase
> (ss
, BaseStation::GetByTile(tile
), tile
, HasBit(ss
->flags
, SSF_CB141_RANDOM_BITS
));
1108 void TriggerStationAnimation(BaseStation
*st
, TileIndex tile
, StationAnimationTrigger trigger
, CargoID cargo_type
)
1110 /* List of coverage areas for each animation trigger */
1111 static const TriggerArea tas
[] = {
1112 TA_TILE
, TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_WHOLE
1115 /* Get Station if it wasn't supplied */
1116 if (st
== NULL
) st
= BaseStation::GetByTile(tile
);
1118 /* Check the cached animation trigger bitmask to see if we need
1119 * to bother with any further processing. */
1120 if (!HasBit(st
->cached_anim_triggers
, trigger
)) return;
1122 uint16 random_bits
= Random();
1123 ETileArea area
= ETileArea(st
, tile
, tas
[trigger
]);
1125 /* Check all tiles over the station to check if the specindex is still in use */
1126 TILE_AREA_LOOP(tile
, area
) {
1127 if (st
->TileBelongsToRailStation(tile
)) {
1128 const StationSpec
*ss
= GetStationSpec(tile
);
1129 if (ss
!= NULL
&& HasBit(ss
->animation
.triggers
, trigger
)) {
1131 if (cargo_type
== CT_INVALID
) {
1134 cargo
= ss
->grf_prop
.grffile
->cargo_map
[cargo_type
];
1136 uint16 callback
= GetStationCallback (CBID_STATION_ANIM_START_STOP
,
1137 (random_bits
<< 16) | Random(),
1138 (uint8
)trigger
| (cargo
<< 8),
1140 AnimationBase::ChangeAnimationFrame (ss
, tile
, callback
);
1147 * Trigger station randomisation
1148 * @param st station being triggered
1149 * @param tile specific tile of platform to trigger
1150 * @param trigger trigger type
1151 * @param cargo_type cargo type causing trigger
1153 void TriggerStationRandomisation(Station
*st
, TileIndex tile
, StationRandomTrigger trigger
, CargoID cargo_type
)
1155 /* List of coverage areas for each animation trigger */
1156 static const TriggerArea tas
[] = {
1157 TA_WHOLE
, TA_WHOLE
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
, TA_PLATFORM
1160 /* Get Station if it wasn't supplied */
1161 if (st
== NULL
) st
= Station::GetByTile(tile
);
1163 /* Check the cached cargo trigger bitmask to see if we need
1164 * to bother with any further processing. */
1165 if (st
->cached_cargo_triggers
== 0) return;
1166 if (cargo_type
!= CT_INVALID
&& !HasBit(st
->cached_cargo_triggers
, cargo_type
)) return;
1168 uint32 whole_reseed
= 0;
1169 ETileArea area
= ETileArea(st
, tile
, tas
[trigger
]);
1171 uint32 empty_mask
= 0;
1172 if (trigger
== SRT_CARGO_TAKEN
) {
1173 /* Create a bitmask of completely empty cargo types to be matched */
1174 for (CargoID i
= 0; i
< NUM_CARGO
; i
++) {
1175 if (st
->goods
[i
].cargo
.TotalCount() == 0) {
1176 SetBit(empty_mask
, i
);
1181 /* Convert trigger to bit */
1182 uint8 trigger_bit
= 1 << trigger
;
1184 /* Check all tiles over the station to check if the specindex is still in use */
1185 TILE_AREA_LOOP(tile
, area
) {
1186 if (st
->TileBelongsToRailStation(tile
)) {
1187 const StationSpec
*ss
= GetStationSpec(tile
);
1188 if (ss
== NULL
) continue;
1190 /* Cargo taken "will only be triggered if all of those
1191 * cargo types have no more cargo waiting." */
1192 if (trigger
== SRT_CARGO_TAKEN
) {
1193 if ((ss
->cargo_triggers
& ~empty_mask
) != 0) continue;
1196 if (cargo_type
== CT_INVALID
|| HasBit(ss
->cargo_triggers
, cargo_type
)) {
1197 StationResolverObject
object(ss
, st
, tile
, CBID_RANDOM_TRIGGER
, 0);
1198 object
.trigger
= trigger_bit
;
1200 const SpriteGroup
*group
= object
.Resolve();
1201 if (group
== NULL
) continue;
1203 uint32 reseed
= object
.GetReseedSum();
1205 whole_reseed
|= reseed
;
1208 /* Set individual tile random bits */
1209 uint8 random_bits
= GetStationTileRandomBits(tile
);
1210 random_bits
&= ~reseed
;
1211 random_bits
|= Random() & reseed
;
1212 SetStationTileRandomBits(tile
, random_bits
);
1214 MarkTileDirtyByTile(tile
);
1220 /* Update whole station random bits */
1221 if ((whole_reseed
& 0xFFFF) != 0) {
1222 st
->random_bits
&= ~whole_reseed
;
1223 st
->random_bits
|= Random() & whole_reseed
;
1228 * Update the cached animation trigger bitmask for a station.
1229 * @param st Station to update.
1231 void StationUpdateCachedTriggers(BaseStation
*st
)
1233 st
->cached_anim_triggers
= 0;
1234 st
->cached_cargo_triggers
= 0;
1236 /* Combine animation trigger bitmask for all station specs
1237 * of this station. */
1238 for (uint i
= 0; i
< st
->num_specs
; i
++) {
1239 const StationSpec
*ss
= st
->speclist
[i
].spec
;
1241 st
->cached_anim_triggers
|= ss
->animation
.triggers
;
1242 st
->cached_cargo_triggers
|= ss
->cargo_triggers
;