Also scroll tile separators in the train depot
[openttd/fttd.git] / src / newgrf_station.cpp
blob4b7a1413ca997d8954daf00a61d6770ea71f975b
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file newgrf_station.cpp Functions for dealing with station classes and custom stations. */
12 #include "stdafx.h"
13 #include "debug.h"
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"
22 #include "town.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"
28 #include "tile_cmd.h"
29 #include "station_func.h"
32 template <>
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);
45 template <>
46 bool NewGRFClass <StationSpec, StationClassID, STAT_CLASS_MAX>::IsUIAvailable (uint index) const
48 return true;
51 INSTANTIATE_NEWGRF_CLASS_METHODS(StationClass)
53 static const uint NUM_STATIONSSPECS_PER_STATION = 255; ///< Maximum number of parts per station.
55 static void MakePlatformArea (TileArea *area, TileIndex tile)
57 Axis axis = GetRailStationAxis (tile);
58 TileIndexDiff delta = TileOffsByDiagDir (AxisToDiagDir (axis));
60 TileIndex ends[2];
61 for (uint i = 0; i < 2; i++, delta = -delta) {
62 TileIndex t = tile;
63 while (IsCompatibleTrainStationTile (t + delta, tile)) {
64 t += delta;
66 ends[i] = t;
69 area->tile = ends[1];
70 area->w = TileX(ends[0]) - TileX(ends[1]) + 1;
71 area->h = TileY(ends[0]) - TileY(ends[1]) + 1;
75 /**
76 * Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
77 * if not centered: .TNLcCpP, if centered: .TNL..CP
78 * - T = Tile layout number (#GetStationGfx)
79 * - N = Number of platforms
80 * - L = Length of platforms
81 * - C = Current platform number from start, c = from end
82 * - P = Position along platform from start, p = from end
83 * .
84 * if centered, C/P start from the centre and c/p are not available.
85 * @return Platform information in bit-stuffed format.
87 uint32 GetPlatformInfo (byte tile, int platforms, int length, int x, int y, bool centred)
89 uint32 retval = 0;
91 if (centred) {
92 x -= platforms / 2;
93 y -= length / 2;
94 x = Clamp(x, -8, 7);
95 y = Clamp(y, -8, 7);
96 SB(retval, 0, 4, y & 0xF);
97 SB(retval, 4, 4, x & 0xF);
98 } else {
99 SB(retval, 0, 4, min(15, y));
100 SB(retval, 4, 4, min(15, length - y - 1));
101 SB(retval, 8, 4, min(15, x));
102 SB(retval, 12, 4, min(15, platforms - x - 1));
104 SB(retval, 16, 4, min(15, length));
105 SB(retval, 20, 4, min(15, platforms));
106 SB(retval, 24, 4, tile);
108 return retval;
113 * Find the end of a railway station, from the \a tile, in the direction of \a delta.
114 * @param tile Start tile.
115 * @param delta Movement direction.
116 * @param check_type Stop when the custom station type changes.
117 * @param check_axis Stop when the station direction changes.
118 * @return Found end of the railway station.
120 static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
122 byte orig_type = 0;
123 Axis orig_axis = AXIS_X;
124 StationID sid = GetStationIndex(tile);
126 if (check_type) orig_type = GetCustomStationSpecIndex(tile);
127 if (check_axis) orig_axis = GetRailStationAxis(tile);
129 for (;;) {
130 TileIndex new_tile = TILE_ADD(tile, delta);
132 if (!IsStationTile(new_tile) || GetStationIndex(new_tile) != sid) break;
133 if (!HasStationRail(new_tile)) break;
134 if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
135 if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
137 tile = new_tile;
139 return tile;
143 static uint32 GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
145 int tx = TileX(tile);
146 int ty = TileY(tile);
147 int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1, 0), check_type, check_axis));
148 int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
149 int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1, 0), check_type, check_axis)) + 1;
150 int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0, 1), check_type, check_axis)) + 1;
152 tx -= sx; ex -= sx;
153 ty -= sy; ey -= sy;
155 if (GetRailStationAxis (tile) == AXIS_X) {
156 Swap(ex, ey);
157 Swap(tx, ty);
160 return GetPlatformInfo (GetStationGfx(tile), ex, ey, tx, ty, centred);
164 static uint32 GetRailContinuationInfo(TileIndex tile)
166 struct DataPair {
167 Direction dir;
168 DiagDirection exit;
171 /* Tile offsets and exit dirs for X axis */
172 static const DataPair data_x[8] = {
173 { DIR_SW, DIAGDIR_SW },
174 { DIR_NE, DIAGDIR_NE },
175 { DIR_SE, DIAGDIR_SE },
176 { DIR_NW, DIAGDIR_NW },
177 { DIR_S, DIAGDIR_SW },
178 { DIR_E, DIAGDIR_NE },
179 { DIR_W, DIAGDIR_SW },
180 { DIR_N, DIAGDIR_NE },
183 /* Tile offsets and exit dirs for Y axis */
184 static const DataPair data_y[8] = {
185 { DIR_SE, DIAGDIR_SE },
186 { DIR_NW, DIAGDIR_NW },
187 { DIR_SW, DIAGDIR_SW },
188 { DIR_NE, DIAGDIR_NE },
189 { DIR_S, DIAGDIR_SE },
190 { DIR_W, DIAGDIR_NW },
191 { DIR_E, DIAGDIR_SE },
192 { DIR_N, DIAGDIR_NW },
195 Axis axis = GetRailStationAxis(tile);
197 /* Choose appropriate lookup table to use */
198 const DataPair *data = (axis == AXIS_X) ? data_x : data_y;
200 uint32 res = 0;
201 for (uint i = 0; i < lengthof(data_x); i++, data++) {
202 TileIndex neighbour_tile = tile + TileOffsByDir (data->dir);
203 TrackBits trackbits = TrackStatusToTrackBits(GetTileRailwayStatus(neighbour_tile));
204 if (trackbits != TRACK_BIT_NONE) {
205 /* If there is any track on the tile, set the bit in the second byte */
206 SetBit(res, i + 8);
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 (IsTunnelTile (neighbour_tile)) {
211 if (GetTunnelBridgeDirection (neighbour_tile) != data->exit) {
212 continue;
214 } else if (IsBridgeHeadTile (neighbour_tile)) {
215 if (GetTunnelBridgeDirection (neighbour_tile) == ReverseDiagDir (data->exit)) {
216 continue;
220 /* If any track reaches our exit direction, set the bit in the lower byte */
221 if (trackbits & DiagdirReachesTracks(data->exit)) SetBit(res, i);
225 return res;
229 /* Station Resolver Functions */
230 /* virtual */ uint32 StationScopeResolver::GetRandomBits() const
232 return this->st->random_bits | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits (this->tile) << 16);
236 /* virtual */ uint32 StationScopeResolver::GetTriggers() const
238 return this->st->waiting_triggers;
243 * Station variable cache
244 * This caches 'expensive' station variable lookups which iterate over
245 * several tiles that may be called multiple times per Resolve().
247 static struct {
248 uint32 v40;
249 uint32 v41;
250 uint32 v45;
251 uint32 v46;
252 uint32 v47;
253 uint32 v49;
254 uint8 valid; ///< Bits indicating what variable is valid (for each bit, \c 0 is invalid, \c 1 is valid).
255 } _svc;
258 * Get the town scope associated with a station, if it exists.
259 * On the first call, the town scope is created (if possible).
260 * @return Town scope, if available.
262 TownScopeResolver *StationResolverObject::GetTown()
264 if (this->town_scope == NULL) {
265 Town *t = this->station_scope.st->town;
266 if (t == NULL) return NULL;
267 this->town_scope = new TownScopeResolver (this->grffile, t, false);
269 return this->town_scope;
272 /* virtual */ uint32 StationScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
274 switch (variable) {
275 /* Calculated station variables */
276 case 0x40:
277 if (!HasBit(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(this->tile, false, false, false); SetBit(_svc.valid, 0); }
278 return _svc.v40;
280 case 0x41:
281 if (!HasBit(_svc.valid, 1)) { _svc.v41 = GetPlatformInfoHelper(this->tile, true, false, false); SetBit(_svc.valid, 1); }
282 return _svc.v41;
284 case 0x42: return GetTerrainType(this->tile) | (GetReverseRailTypeTranslation(GetRailType(this->tile), this->statspec->grf_prop.grffile) << 8);
285 case 0x43: return GetCompanyInfo(this->st->owner); // Station owner
286 case 0x44: return HasStationReservation(this->tile) ? 7 : 4; // PBS status
287 case 0x45:
288 if (!HasBit(_svc.valid, 2)) { _svc.v45 = GetRailContinuationInfo(this->tile); SetBit(_svc.valid, 2); }
289 return _svc.v45;
291 case 0x46:
292 if (!HasBit(_svc.valid, 3)) { _svc.v46 = GetPlatformInfoHelper(this->tile, false, false, true); SetBit(_svc.valid, 3); }
293 return _svc.v46;
295 case 0x47:
296 if (!HasBit(_svc.valid, 4)) { _svc.v47 = GetPlatformInfoHelper(this->tile, true, false, true); SetBit(_svc.valid, 4); }
297 return _svc.v47;
299 case 0x49:
300 if (!HasBit(_svc.valid, 5)) { _svc.v49 = GetPlatformInfoHelper(this->tile, false, true, false); SetBit(_svc.valid, 5); }
301 return _svc.v49;
303 case 0x4A: // Animation frame of tile
304 return GetAnimationFrame(this->tile);
306 /* Variables which use the parameter */
307 /* Variables 0x60 to 0x65 and 0x69 are handled separately below */
308 case 0x66: { // Animation frame of nearby tile
309 TileIndex tile = this->tile;
310 if (parameter != 0) tile = GetNearbyTile(parameter, tile);
311 return this->st->TileBelongsToRailStation(tile) ? GetAnimationFrame(tile) : UINT_MAX;
314 case 0x67: { // Land info of nearby tile
315 Axis axis = GetRailStationAxis(this->tile);
316 TileIndex tile = this->tile;
317 if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
319 Slope tileh = GetTileSlope(tile);
320 bool swap = (axis == AXIS_Y && HasBit(tileh, CORNER_W) != HasBit(tileh, CORNER_E));
322 return GetNearbyTileInformation (tile, this->grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
325 case 0x68: { // Station info of nearby tiles
326 TileIndex nearby_tile = GetNearbyTile(parameter, this->tile);
328 if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
330 uint32 grfid = this->st->speclist[GetCustomStationSpecIndex(this->tile)].grfid;
331 bool perpendicular = GetRailStationAxis(this->tile) != GetRailStationAxis(nearby_tile);
332 bool same_station = this->st->TileBelongsToRailStation(nearby_tile);
333 uint32 res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
335 uint spec_index = GetCustomStationSpecIndex (nearby_tile);
336 if (spec_index != 0) {
337 const StationSpecList ssl = BaseStation::GetByTile(nearby_tile)->speclist[spec_index];
338 res |= 1 << (ssl.grfid != grfid ? 9 : 8) | ssl.localidx;
340 return res;
343 /* General station variables */
344 case 0x82: return 50;
345 case 0x84: return this->st->string_id;
346 case 0x86: return 0;
347 case 0xF0: return this->st->facilities;
348 case 0xFA: return Clamp(this->st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
351 return this->st->GetNewGRFVariable (this->grffile, variable, parameter, available);
354 uint32 Station::GetNewGRFVariable (const GRFFile *grffile, byte variable, byte parameter, bool *available) const
356 switch (variable) {
357 case 0x48: { // Accepted cargo types
358 CargoID cargo_type;
359 uint32 value = 0;
361 for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
362 if (HasBit(this->goods[cargo_type].status, GoodsEntry::GES_ACCEPTANCE)) SetBit(value, cargo_type);
364 return value;
367 case 0x8A: return this->had_vehicle_of_type;
368 case 0xF1: return (this->airport.tile != INVALID_TILE) ? this->airport.GetSpec()->ttd_airport_type : ATP_TTDP_LARGE;
369 case 0xF2: return (this->truck_stops != NULL) ? this->truck_stops->status : 0;
370 case 0xF3: return (this->bus_stops != NULL) ? this->bus_stops->status : 0;
371 case 0xF6: return this->airport.flags;
372 case 0xF7: return GB(this->airport.flags, 8, 8);
375 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
376 if ((variable >= 0x60 && variable <= 0x65) || variable == 0x69) {
377 CargoID c = GetCargoTranslation (parameter, grffile);
379 if (c == CT_INVALID) {
380 switch (variable) {
381 case 0x62: return 0xFFFFFFFF;
382 case 0x64: return 0xFF00;
383 default: return 0;
386 const GoodsEntry *ge = &this->goods[c];
388 switch (variable) {
389 case 0x60: return min(ge->cargo.TotalCount(), 4095);
390 case 0x61: return ge->HasVehicleEverTriedLoading() ? ge->time_since_pickup : 0;
391 case 0x62: return ge->HasRating() ? ge->rating : 0xFFFFFFFF;
392 case 0x63: return ge->cargo.DaysInTransit();
393 case 0x64: return ge->HasVehicleEverTriedLoading() ? ge->last_speed | (ge->last_age << 8) : 0xFF00;
394 case 0x65: return GB(ge->status, GoodsEntry::GES_ACCEPTANCE, 1) << 3;
395 case 0x69: {
396 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 1 == (int)GoodsEntry::GES_LAST_MONTH);
397 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 2 == (int)GoodsEntry::GES_CURRENT_MONTH);
398 assert_compile((int)GoodsEntry::GES_EVER_ACCEPTED + 3 == (int)GoodsEntry::GES_ACCEPTED_BIGTICK);
399 return GB(ge->status, GoodsEntry::GES_EVER_ACCEPTED, 4);
404 /* Handle cargo variables (deprecated) */
405 if (variable >= 0x8C && variable <= 0xEC) {
406 const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
407 switch (GB(variable - 0x8C, 0, 3)) {
408 case 0: return g->cargo.TotalCount();
409 case 1: return GB(min(g->cargo.TotalCount(), 4095), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
410 case 2: return g->time_since_pickup;
411 case 3: return g->rating;
412 case 4: return g->cargo.Source();
413 case 5: return g->cargo.DaysInTransit();
414 case 6: return g->last_speed;
415 case 7: return g->last_age;
419 DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
421 *available = false;
422 return UINT_MAX;
425 uint32 Waypoint::GetNewGRFVariable (const GRFFile *grffile, byte variable, byte parameter, bool *available) const
427 switch (variable) {
428 case 0x48: return 0; // Accepted cargo types
429 case 0x8A: return HVOT_WAYPOINT;
430 case 0xF1: return 0; // airport type
431 case 0xF2: return 0; // truck stop status
432 case 0xF3: return 0; // bus stop status
433 case 0xF6: return 0; // airport flags
434 case 0xF7: return 0; // airport flags cont.
437 /* Handle cargo variables with parameter, 0x60 to 0x65 */
438 if (variable >= 0x60 && variable <= 0x65) {
439 return 0;
442 /* Handle cargo variables (deprecated) */
443 if (variable >= 0x8C && variable <= 0xEC) {
444 switch (GB(variable - 0x8C, 0, 3)) {
445 case 3: return INITIAL_STATION_RATING;
446 case 4: return INVALID_STATION;
447 default: return 0;
451 DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
453 *available = false;
454 return UINT_MAX;
457 /* virtual */ const SpriteGroup *StationResolverObject::ResolveReal(const RealSpriteGroup *group) const
459 if (this->station_scope.statspec->cls_id == STAT_CLASS_WAYP) {
460 return group->get_first (true);
463 uint cargo = 0;
464 const Station *st = Station::From(this->station_scope.st);
466 switch (this->station_scope.cargo_type) {
467 case CT_INVALID:
468 case CT_DEFAULT_NA:
469 case CT_PURCHASE:
470 cargo = 0;
471 break;
473 case CT_DEFAULT:
474 for (CargoID cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
475 cargo += st->goods[cargo_type].cargo.TotalCount();
477 break;
479 default:
480 cargo = st->goods[this->station_scope.cargo_type].cargo.TotalCount();
481 break;
484 if (HasBit(this->station_scope.statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
485 cargo = min(0xfff, cargo);
487 uint threshold = this->station_scope.statspec->cargo_threshold;
488 if (cargo > threshold) {
489 uint count = group->get_count (true);
490 if (count > 0) {
491 uint set = ((cargo - threshold) * count) / (4096 - threshold);
492 return group->get_group (true, set);
494 } else {
495 uint count = group->get_count (false);
496 if (count > 0) {
497 uint set = (cargo * count) / (threshold + 1);
498 return group->get_group (false, set);
502 return group->get_first (false);
506 * Resolver for stations.
507 * @param statspec Station (type) specification.
508 * @param st Instance of the station.
509 * @param tile %Tile of the station.
510 * @param callback Callback ID.
511 * @param callback_param1 First parameter (var 10) of the callback.
512 * @param callback_param2 Second parameter (var 18) of the callback.
514 StationResolverObject::StationResolverObject(const StationSpec *statspec, BaseStation *st, TileIndex tile,
515 CallbackID callback, uint32 callback_param1, uint32 callback_param2)
516 : ResolverObject(statspec->grf_prop.grffile, callback, callback_param1, callback_param2),
517 station_scope (this->grffile, statspec, st, tile), town_scope(NULL)
519 assert (st != NULL);
521 /* Invalidate all cached vars */
522 _svc.valid = 0;
524 CargoID ctype = CT_DEFAULT_NA;
526 if (!this->station_scope.st->IsWaypoint()) {
527 const Station *st = Station::From(this->station_scope.st);
528 /* Pick the first cargo that we have waiting */
529 const CargoSpec *cs;
530 FOR_ALL_CARGOSPECS(cs) {
531 if (this->station_scope.statspec->spritegroup[cs->Index()] != NULL &&
532 st->goods[cs->Index()].cargo.TotalCount() > 0) {
533 ctype = cs->Index();
534 break;
539 if (this->station_scope.statspec->spritegroup[ctype] == NULL) {
540 ctype = CT_DEFAULT;
543 /* Remember the cargo type we've picked */
544 this->station_scope.cargo_type = ctype;
545 this->root_spritegroup = this->station_scope.statspec->spritegroup[this->station_scope.cargo_type];
548 StationResolverObject::~StationResolverObject()
550 delete this->town_scope;
554 * Constructor for station scopes.
555 * @param grffile GRFFile the resolved SpriteGroup belongs to.
556 * @param statspec Station (type) specification.
557 * @param st Instance of the station.
558 * @param tile %Tile of the station.
560 StationScopeResolver::StationScopeResolver (const GRFFile *grffile, const StationSpec *statspec, BaseStation *st, TileIndex tile)
561 : ScopeResolver(), grffile(grffile)
563 assert (st != NULL);
565 this->tile = tile;
566 this->st = st;
567 this->statspec = statspec;
568 this->cargo_type = CT_INVALID;
572 /** Scope resolver for stations not yet built. */
573 struct FakeStationScopeResolver : public ScopeResolver {
574 const GRFFile *const grffile; ///< GRFFile the resolved SpriteGroup belongs to.
575 TileIndex tile; ///< %Tile of the station.
576 const struct StationSpec *statspec; ///< Station (type) specification.
577 RailType railtype; ///< Rail type.
578 Axis axis; ///< Station axis, used only for the slope check callback.
580 FakeStationScopeResolver (const GRFFile *grffile, const StationSpec *statspec,
581 TileIndex tile, RailType rt, Axis axis = INVALID_AXIS)
582 : ScopeResolver(), grffile(grffile), tile(tile),
583 statspec(statspec), railtype(rt), axis(axis)
587 uint32 GetVariable (byte variable, uint32 parameter, bool *available) const OVERRIDE;
590 uint32 FakeStationScopeResolver::GetVariable (byte variable, uint32 parameter, bool *available) const
592 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
593 switch (variable) {
594 case 0x40:
595 case 0x41:
596 case 0x46:
597 case 0x47:
598 case 0x49: return 0x2110000; // Platforms, tracks & position
599 case 0x42: return GetReverseRailTypeTranslation (this->railtype, this->statspec->grf_prop.grffile) << 8;
600 case 0x43: return GetCompanyInfo (_current_company); // Station owner
601 case 0x44: return 2; // PBS status
602 case 0x67: // Land info of nearby tile
603 if (this->axis != INVALID_AXIS && this->tile != INVALID_TILE) {
604 TileIndex tile = this->tile;
605 if (parameter != 0) tile = GetNearbyTile (parameter, tile, true, this->axis); // only perform if it is required
607 Slope tileh = GetTileSlope(tile);
608 bool swap = (this->axis == AXIS_Y && HasBit(tileh, CORNER_W) != HasBit(tileh, CORNER_E));
610 return GetNearbyTileInformation (tile, this->grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
612 break;
614 case 0xFA: return Clamp (_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
617 *available = false;
618 return UINT_MAX;
621 /** Resolver for stations not yet built. */
622 struct FakeStationResolverObject : public ResolverObject {
623 FakeStationScopeResolver station_scope; ///< The station scope resolver.
624 TownScopeResolver *town_scope; ///< The town scope resolver (created on the first call).
626 const SpriteGroup *root_spritegroup; ///< Root SpriteGroup to use for resolving
629 * Resolver for stations not yet built.
630 * @param statspec Station (type) specification.
631 * @param tile %Tile of the station.
632 * @param rt Rail type.
633 * @param callback Callback ID.
634 * @param callback_param1 First parameter (var 10) of the callback.
635 * @param callback_param2 Second parameter (var 18) of the callback.
636 * @param axis Axis of the station tile to build, if any.
638 FakeStationResolverObject (const StationSpec *statspec, TileIndex tile,
639 RailType rt, CallbackID callback = CBID_NO_CALLBACK,
640 uint32 callback_param1 = 0, uint32 callback_param2 = 0,
641 Axis axis = INVALID_AXIS)
642 : ResolverObject (statspec->grf_prop.grffile,
643 callback, callback_param1, callback_param2),
644 station_scope (this->grffile, statspec, tile, rt, axis),
645 town_scope (NULL)
647 /* Invalidate all cached vars */
648 _svc.valid = 0;
650 /* No station, so we are in a purchase list */
651 const SpriteGroup *const *groups = statspec->spritegroup;
652 const SpriteGroup *root = groups[CT_PURCHASE];
654 if (root == NULL) {
655 root = groups[CT_DEFAULT];
658 this->root_spritegroup = root;
661 ~FakeStationResolverObject();
663 TownScopeResolver *GetTown (void);
665 ScopeResolver *GetScope (VarSpriteGroupScope scope = VSG_SCOPE_SELF, byte relative = 0) OVERRIDE
667 switch (scope) {
668 case VSG_SCOPE_SELF:
669 return &this->station_scope;
671 case VSG_SCOPE_PARENT: {
672 TownScopeResolver *tsr = this->GetTown();
673 if (tsr != NULL) return tsr;
675 FALLTHROUGH;
677 default:
678 return ResolverObject::GetScope (scope, relative);
682 const SpriteGroup *ResolveReal (const RealSpriteGroup *group) const OVERRIDE
684 return group->get_first (true);
688 * Resolve SpriteGroup.
689 * @return Result spritegroup.
691 const SpriteGroup *Resolve (void)
693 return SpriteGroup::Resolve (this->root_spritegroup, *this);
697 FakeStationResolverObject::~FakeStationResolverObject()
699 delete this->town_scope;
703 * Get the town scope associated with a station, if it exists.
704 * On the first call, the town scope is created (if possible).
705 * @return Town scope, if available.
707 TownScopeResolver *FakeStationResolverObject::GetTown (void)
709 if (this->town_scope == NULL) {
710 Town *t = NULL;
711 if (this->station_scope.tile != INVALID_TILE) {
712 t = ClosestTownFromTile(this->station_scope.tile);
714 if (t == NULL) return NULL;
715 this->town_scope = new TownScopeResolver (this->grffile, t, true);
717 return this->town_scope;
722 * Resolve sprites for drawing a station tile.
723 * @param statspec Station spec
724 * @param st Station
725 * @param tile Station tile being drawn
726 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
727 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
729 SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32 var10)
731 assert (st != NULL);
732 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, var10);
733 const SpriteGroup *group = object.Resolve();
734 if (group == NULL || !group->IsType (SGT_RESULT)) return 0;
735 return group->GetResult() - 0x42D;
739 * Resolve sprites for drawing a station tile in the GUI.
740 * @param statspec Station spec
741 * @param rt Rail type.
742 * @param var10 Value to put in variable 10; normally 0; 1 when resolving the groundsprite and SSF_SEPARATE_GROUND is set.
743 * @return First sprite of the Action 1 spriteset to use, minus an offset of 0x42D to accommodate for weird NewGRF specs.
745 static SpriteID GetCustomStationRelocation (const StationSpec *statspec,
746 RailType rt, uint32 var10)
748 FakeStationResolverObject object (statspec, INVALID_TILE, rt, CBID_NO_CALLBACK, var10);
749 const SpriteGroup *group = object.Resolve();
750 if (group == NULL || !group->IsType (SGT_RESULT)) return 0;
751 return group->GetResult() - 0x42D;
755 * Resolve the sprites for custom station foundations.
756 * @param statspec Station spec
757 * @param st Station
758 * @param tile Station tile being drawn
759 * @param layout Spritelayout as returned by previous callback
760 * @param edge_info Information about northern tile edges; whether they need foundations or merge into adjacent tile's foundations.
761 * @return First sprite of a set of foundation sprites for various slopes, or 0 if default foundations shall be drawn.
763 SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
765 /* callback_param1 == 2 means we are resolving the foundation sprites. */
766 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, 2, layout | (edge_info << 16));
768 const SpriteGroup *group = object.Resolve();
769 if (group == NULL || !group->IsType (SGT_RESULT)) return 0;
771 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
772 return group->GetResult() + GetRegister(0x100);
776 uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, BaseStation *st, TileIndex tile)
778 assert (st != NULL);
779 StationResolverObject object(statspec, st, tile, callback, param1, param2);
780 return SpriteGroup::CallbackResult (object.Resolve());
783 uint16 GetStationCallback (CallbackID callback, uint32 param1, uint32 param2,
784 const StationSpec *statspec, RailType rt, TileIndex tile)
786 FakeStationResolverObject object (statspec, tile, rt, callback, param1, param2);
787 return SpriteGroup::CallbackResult (object.Resolve());
791 * Check the slope of a tile of a new station.
792 * @param north_tile Norther tile of the station rect.
793 * @param cur_tile Tile to check.
794 * @param statspec Station spec.
795 * @param rt Rail type.
796 * @param axis Axis of the new station.
797 * @param plat_len Platform length.
798 * @param numtracks Number of platforms.
799 * @return Succeeded or failed command.
801 CommandCost PerformStationTileSlopeCheck (TileIndex north_tile,
802 TileIndex cur_tile, const StationSpec *statspec, RailType rt,
803 Axis axis, byte plat_len, byte numtracks)
805 TileIndexDiff diff = cur_tile - north_tile;
806 Slope slope = GetTileSlope(cur_tile);
808 FakeStationResolverObject object (statspec, cur_tile, rt, CBID_STATION_LAND_SLOPE_CHECK,
809 (slope << 4) | (slope ^ (axis == AXIS_Y && HasBit(slope, CORNER_W) != HasBit(slope, CORNER_E) ? SLOPE_EW : 0)),
810 (numtracks << 24) | (plat_len << 16) | (axis == AXIS_Y ? TileX(diff) << 8 | TileY(diff) : TileY(diff) << 8 | TileX(diff)),
811 axis);
813 uint16 cb_res = SpriteGroup::CallbackResult (object.Resolve());
815 /* Failed callback means success. */
816 if (cb_res == CALLBACK_FAILED) return CommandCost();
818 /* The meaning of bit 10 is inverted for a grf version < 8. */
819 if (statspec->grf_prop.grffile->grf_version < 8) ToggleBit(cb_res, 10);
820 return GetErrorMessageFromLocationCallbackResult(cb_res, statspec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
825 * Allocate a StationSpec to a Station. This is called once per build operation.
826 * @param statspec StationSpec to allocate.
827 * @param st Station to allocate it to.
828 * @param exec Whether to actually allocate the spec.
829 * @return Index within the Station's spec list, or -1 if the allocation failed.
831 int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
833 uint i;
835 if (statspec == NULL || st == NULL) return 0;
837 for (i = 1; i < st->num_specs && i < NUM_STATIONSSPECS_PER_STATION; i++) {
838 if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
841 if (i == NUM_STATIONSSPECS_PER_STATION) {
842 /* As final effort when the spec list is already full...
843 * try to find the same spec and return that one. This might
844 * result in slightly "wrong" (as per specs) looking stations,
845 * but it's fairly unlikely that one reaches the limit anyways.
847 for (i = 1; i < st->num_specs && i < NUM_STATIONSSPECS_PER_STATION; i++) {
848 if (st->speclist[i].spec == statspec) return i;
851 return -1;
854 if (exec) {
855 if (i >= st->num_specs) {
856 st->num_specs = i + 1;
857 st->speclist = xrealloct (st->speclist, st->num_specs);
859 if (st->num_specs == 2) {
860 /* Initial allocation */
861 st->speclist[0].spec = NULL;
862 st->speclist[0].grfid = 0;
863 st->speclist[0].localidx = 0;
867 st->speclist[i].spec = statspec;
868 st->speclist[i].grfid = statspec->grf_prop.grffile->grfid;
869 st->speclist[i].localidx = statspec->grf_prop.local_id;
871 StationUpdateCachedTriggers(st);
874 return i;
879 * Deallocate a StationSpec from a Station. Called when removing a single station tile.
880 * @param st Station to work with.
881 * @param specindex Index of the custom station within the Station's spec list.
882 * @return Indicates whether the StationSpec was deallocated.
884 void DeallocateSpecFromStation(BaseStation *st, byte specindex)
886 /* specindex of 0 (default) is never freeable */
887 if (specindex == 0) return;
889 /* Check all tiles over the station to check if the specindex is still in use */
890 TILE_AREA_LOOP(tile, st->train_station) {
891 if (st->TileBelongsToRailStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
892 return;
896 /* This specindex is no longer in use, so deallocate it */
897 st->speclist[specindex].spec = NULL;
898 st->speclist[specindex].grfid = 0;
899 st->speclist[specindex].localidx = 0;
901 /* If this was the highest spec index, reallocate */
902 if (specindex == st->num_specs - 1) {
903 for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
905 if (st->num_specs > 1) {
906 st->speclist = xrealloct (st->speclist, st->num_specs);
907 } else {
908 free(st->speclist);
909 st->num_specs = 0;
910 st->speclist = NULL;
911 st->cached_anim_triggers = 0;
912 st->cached_cargo_triggers = 0;
913 return;
917 StationUpdateCachedTriggers(st);
921 * Draw representation of a station tile for GUI purposes.
922 * @param dpi The area to draw on.
923 * @param x Position x of image.
924 * @param y Position y of image.
925 * @param axis Axis.
926 * @param railtype Rail type.
927 * @param sclass, station Type of station.
928 * @param station station ID
929 * @return True if the tile was drawn (allows for fallback to default graphic)
931 bool DrawStationTile (BlitArea *dpi, int x, int y, RailType railtype,
932 Axis axis, StationClassID sclass, uint station)
934 const DrawTileSprites *sprites = NULL;
935 const RailtypeInfo *rti = GetRailTypeInfo(railtype);
936 PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
937 uint tile = 2;
939 const StationSpec *statspec = StationClass::Get(sclass)->GetSpec(station);
940 if (statspec == NULL) return false;
942 if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
943 uint16 callback = GetStationCallback (CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, railtype);
944 if (callback != CALLBACK_FAILED) tile = callback;
947 uint32 total_offset = rti->GetRailtypeSpriteOffset();
948 uint32 relocation = 0;
949 uint32 ground_relocation = 0;
950 const NewGRFSpriteLayout *layout = NULL;
952 if (statspec->renderdata.empty()) {
953 sprites = GetDefaultStationTileLayout() + (tile + axis);
954 } else {
955 uint t = (tile < statspec->renderdata.size()) ? tile : 0;
956 layout = statspec->renderdata[t + axis].get();
957 if (!layout->NeedsPreprocessing()) {
958 sprites = layout;
959 layout = NULL;
963 NewGRFSpriteLayout::Result result;
964 PalSpriteID ground;
965 const DrawTileSeqStruct *seq;
966 if (layout != NULL) {
967 /* Sprite layout which needs preprocessing */
968 bool separate_ground = HasBit(statspec->flags, SSF_SEPARATE_GROUND);
969 uint32 var10_values = result.prepare (layout, 0, total_offset, rti->fallback_railtype, separate_ground);
970 uint8 var10;
971 FOR_EACH_SET_BIT(var10, var10_values) {
972 uint32 var10_relocation = GetCustomStationRelocation (statspec, railtype, var10);
973 result.process (layout, var10, var10_relocation, separate_ground);
975 ground = result.get_ground();
976 seq = result.get_seq();
977 total_offset = 0;
978 } else {
979 /* Simple sprite layout */
980 ground = sprites->ground;
981 seq = sprites->seq;
982 ground_relocation = relocation = GetCustomStationRelocation (statspec, railtype, 0);
983 if (HasBit(ground.sprite, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
984 ground_relocation = GetCustomStationRelocation (statspec, railtype, 1);
986 ground_relocation += rti->fallback_railtype;
989 SpriteID image = ground.sprite;
990 PaletteID pal = ground.pal;
991 RailTrackOffset overlay_offset;
992 if (rti->UsesOverlay() && SplitGroundSpriteForOverlay (&image, &overlay_offset)) {
993 SpriteID ground = GetCustomRailSprite(rti, INVALID_TILE, RTSG_GROUND);
994 DrawSprite (dpi, image, PAL_NONE, x, y);
995 DrawSprite (dpi, ground + overlay_offset, PAL_NONE, x, y);
996 } else {
997 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
998 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
999 DrawSprite (dpi, image, GroundSpritePaletteTransform (image, pal, palette), x, y);
1002 DrawRailTileSeqInGUI (dpi, x, y, seq, total_offset, relocation, palette);
1004 return true;
1008 const StationSpec *GetStationSpec(TileIndex t)
1010 uint specindex = GetCustomStationSpecIndex(t);
1011 if (specindex == 0) return NULL;
1013 const BaseStation *st = BaseStation::GetByTile(t);
1014 return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
1019 * Check whether a rail station tile is NOT traversable.
1020 * @param tile %Tile to test.
1021 * @return Station tile is blocked.
1022 * @note This could be cached (during build) in the map array to save on all the dereferencing.
1024 bool IsStationTileBlocked(TileIndex tile)
1026 const StationSpec *statspec = GetStationSpec(tile);
1028 return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
1031 /** Helper class for animation control. */
1032 struct StationAnimationBase {
1033 static const CallbackID cb_animation_speed = CBID_STATION_ANIMATION_SPEED;
1034 static const CallbackID cb_animation_next_frame = CBID_STATION_ANIM_NEXT_FRAME;
1036 static const StationCallbackMask cbm_animation_speed = CBM_STATION_ANIMATION_SPEED;
1037 static const StationCallbackMask cbm_animation_next_frame = CBM_STATION_ANIMATION_NEXT_FRAME;
1039 /** Callback wrapper for animation control. */
1040 static uint16 get_callback (CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, BaseStation *st, TileIndex tile)
1042 return GetStationCallback (callback, param1, param2, statspec, st, tile);
1046 void AnimateStationTile(TileIndex tile)
1048 const StationSpec *ss = GetStationSpec(tile);
1049 if (ss == NULL) return;
1051 AnimationBase::AnimateTile <StationAnimationBase> (ss, BaseStation::GetByTile(tile), tile, HasBit(ss->flags, SSF_CB141_RANDOM_BITS));
1054 void TriggerStationAnimation(BaseStation *st, TileIndex tile, StationAnimationTrigger trigger, CargoID cargo_type)
1056 /* Bitmask of animation triggers that affect the whole station. */
1057 static const uint whole = (1 << SAT_NEW_CARGO)
1058 | (1 << SAT_CARGO_TAKEN)
1059 | (1 << SAT_250_TICKS);
1061 /* Get Station if it wasn't supplied */
1062 if (st == NULL) st = BaseStation::GetByTile(tile);
1064 /* Check the cached animation trigger bitmask to see if we need
1065 * to bother with any further processing. */
1066 if (!HasBit(st->cached_anim_triggers, trigger)) return;
1068 uint16 random_bits = Random();
1069 TileArea area;
1070 if (trigger == SAT_BUILT) {
1071 area.tile = tile;
1072 area.w = 1;
1073 area.h = 1;
1074 } else if (HasBit(whole, trigger)) {
1075 area = st->train_station;
1076 } else {
1077 MakePlatformArea (&area, tile);
1080 /* Check all tiles over the station to check if the specindex is still in use */
1081 TILE_AREA_LOOP(tile, area) {
1082 if (st->TileBelongsToRailStation(tile)) {
1083 const StationSpec *ss = GetStationSpec(tile);
1084 if (ss != NULL && HasBit(ss->animation.triggers, trigger)) {
1085 CargoID cargo;
1086 if (cargo_type == CT_INVALID) {
1087 cargo = CT_INVALID;
1088 } else {
1089 cargo = ss->grf_prop.grffile->cargo_map[cargo_type];
1091 uint16 callback = GetStationCallback (CBID_STATION_ANIM_START_STOP,
1092 (random_bits << 16) | Random(),
1093 (uint8)trigger | (cargo << 8),
1094 ss, st, tile);
1095 AnimationBase::ChangeAnimationFrame (ss, tile, callback);
1102 * Trigger station randomisation
1103 * @param st station being triggered
1104 * @param tile specific tile of platform to trigger
1105 * @param trigger trigger type
1106 * @param cargo_type cargo type causing trigger
1108 void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
1110 /* Bitmask of randomisation triggers that affect the whole station. */
1111 static const uint whole = (1 << SRT_NEW_CARGO)
1112 | (1 << SRT_CARGO_TAKEN);
1114 /* Get Station if it wasn't supplied */
1115 if (st == NULL) st = Station::GetByTile(tile);
1117 /* Check the cached cargo trigger bitmask to see if we need
1118 * to bother with any further processing. */
1119 if (st->cached_cargo_triggers == 0) return;
1120 if (cargo_type != CT_INVALID && !HasBit(st->cached_cargo_triggers, cargo_type)) return;
1122 uint32 whole_reseed = 0;
1124 uint32 cargo_mask = 0;
1125 if (trigger == SRT_CARGO_TAKEN) {
1126 /* Create a bitmask of completely empty cargo types to be matched */
1127 uint32 empty_mask = 0;
1128 for (CargoID i = 0; i < NUM_CARGO; i++) {
1129 if (st->goods[i].cargo.TotalCount() == 0) {
1130 SetBit(empty_mask, i);
1133 cargo_mask = ~empty_mask;
1136 /* Store triggers now for var 5F */
1137 uint8 trigger_bit = 1 << trigger;
1138 st->waiting_triggers |= trigger_bit;
1139 uint32 used_triggers = 0;
1141 TileArea area;
1142 if ((whole & trigger_bit) != 0) {
1143 area = st->train_station;
1144 } else {
1145 MakePlatformArea (&area, tile);
1148 /* Check all tiles over the station to check if the specindex is still in use */
1149 TILE_AREA_LOOP(tile, area) {
1150 if (st->TileBelongsToRailStation(tile)) {
1151 const StationSpec *ss = GetStationSpec(tile);
1152 if (ss == NULL) continue;
1154 /* Cargo taken "will only be triggered if all of those
1155 * cargo types have no more cargo waiting." */
1156 if ((ss->cargo_triggers & cargo_mask) != 0) continue;
1158 if (cargo_type == CT_INVALID || HasBit(ss->cargo_triggers, cargo_type)) {
1159 StationResolverObject object(ss, st, tile, CBID_RANDOM_TRIGGER, 0);
1160 object.waiting_triggers = st->waiting_triggers;
1162 const SpriteGroup *group = object.Resolve();
1163 if (group == NULL) continue;
1165 used_triggers |= object.used_triggers;
1167 uint32 reseed = object.GetReseedSum();
1168 if (reseed != 0) {
1169 whole_reseed |= reseed;
1170 reseed >>= 16;
1172 /* Set individual tile random bits */
1173 uint8 random_bits = GetStationTileRandomBits(tile);
1174 random_bits &= ~reseed;
1175 random_bits |= Random() & reseed;
1176 SetStationTileRandomBits(tile, random_bits);
1178 MarkTileDirtyByTile(tile);
1184 /* Update whole station random bits */
1185 st->waiting_triggers &= ~used_triggers;
1186 if ((whole_reseed & 0xFFFF) != 0) {
1187 st->random_bits &= ~whole_reseed;
1188 st->random_bits |= Random() & whole_reseed;
1193 * Update the cached animation trigger bitmask for a station.
1194 * @param st Station to update.
1196 void StationUpdateCachedTriggers(BaseStation *st)
1198 st->cached_anim_triggers = 0;
1199 st->cached_cargo_triggers = 0;
1201 /* Combine animation trigger bitmask for all station specs
1202 * of this station. */
1203 for (uint i = 0; i < st->num_specs; i++) {
1204 const StationSpec *ss = st->speclist[i].spec;
1205 if (ss != NULL) {
1206 st->cached_anim_triggers |= ss->animation.triggers;
1207 st->cached_cargo_triggers |= ss->cargo_triggers;