OpenTTD Source 20261112-master-gbcbec5e63f
newgrf_station.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "debug.h"
12#include "station_base.h"
13#include "station_func.h"
14#include "waypoint_base.h"
15#include "roadstop_base.h"
16#include "newgrf_badge.h"
17#include "newgrf_cargo.h"
18#include "newgrf_station.h"
19#include "newgrf_spritegroup.h"
20#include "newgrf_railtype.h"
21#include "town.h"
22#include "newgrf_town.h"
23#include "company_func.h"
24#include "tunnelbridge_map.h"
27#include "tile_cmd.h"
28
29#include "table/strings.h"
30
31#include "newgrf_class_func.h"
32
33#include "safeguards.h"
34
35
36template <>
45
46template <>
48{
49 return true;
50}
51
52/* Instantiate StationClass. */
54
55static const uint NUM_STATIONSSPECS_PER_STATION = 255;
56
62{
63 uint8_t res = 0;
64 if (this->status.Test(GoodsEntry::State::EverAccepted)) SetBit(res, 0);
65 if (this->status.Test(GoodsEntry::State::LastMonth)) SetBit(res, 1);
66 if (this->status.Test(GoodsEntry::State::CurrentMonth)) SetBit(res, 2);
67 if (this->status.Test(GoodsEntry::State::AcceptedBigtick)) SetBit(res, 3);
68 return res;
69}
70
79{
80 switch (ta) {
81 default: NOT_REACHED();
82
84 return {tile, 1, 1};
85
87 TileIndex start, end;
88 Axis axis = GetRailStationAxis(tile);
89 TileIndexDiff delta = TileOffsByAxis(axis);
90
91 for (end = tile; IsRailStationTile(end + delta) && IsCompatibleTrainStationTile(end + delta, tile); end += delta) { /* Nothing */ }
92 for (start = tile; IsRailStationTile(start - delta) && IsCompatibleTrainStationTile(start - delta, tile); start -= delta) { /* Nothing */ }
93
94 return TileArea(start, TileX(end) - TileX(start) + 1, TileY(end) - TileY(start) + 1);
95 }
96
99 }
100}
101
102
121uint32_t GetPlatformInfo(StationGfx gfx, int platforms, int length, int platform, int position, bool centred)
122{
123 uint32_t retval = 0;
124
125 if (centred) {
126 platform -= platforms / 2;
127 position -= length / 2;
128 platform = Clamp(platform, -8, 7);
129 position = Clamp(position, -8, 7);
130 SB(retval, 0, 4, position & 0xF);
131 SB(retval, 4, 4, platform & 0xF);
132 } else {
133 SB(retval, 0, 4, std::min(15, position));
134 SB(retval, 4, 4, std::min(15, length - position - 1));
135 SB(retval, 8, 4, std::min(15, platform));
136 SB(retval, 12, 4, std::min(15, platforms - platform - 1));
137 }
138 SB(retval, 16, 4, std::min(15, length));
139 SB(retval, 20, 4, std::min(15, platforms));
140 SB(retval, 24, 8, gfx);
141
142 return retval;
143}
144
145
154static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
155{
156 uint8_t orig_type = 0;
157 Axis orig_axis = Axis::X;
158 StationID sid = GetStationIndex(tile);
159
160 if (check_type) orig_type = GetCustomStationSpecIndex(tile);
161 if (check_axis) orig_axis = GetRailStationAxis(tile);
162
163 for (;;) {
164 TileIndex new_tile = TileAdd(tile, delta);
165
166 if (!IsTileType(new_tile, TileType::Station) || GetStationIndex(new_tile) != sid) break;
167 if (!HasStationRail(new_tile)) break;
168 if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
169 if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
170
171 tile = new_tile;
172 }
173 return tile;
174}
175
176
177static uint32_t GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
178{
179 int tx = TileX(tile);
180 int ty = TileY(tile);
181 int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1, 0), check_type, check_axis));
182 int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
183 int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1, 0), check_type, check_axis)) + 1;
184 int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0, 1), check_type, check_axis)) + 1;
185
186 tx -= sx; ex -= sx;
187 ty -= sy; ey -= sy;
188
189 if (GetRailStationAxis(tile) == Axis::X) {
190 std::swap(ex, ey);
191 std::swap(tx, ty);
192 }
193
194 return GetPlatformInfo(GetStationGfx(tile), ex, ey, tx, ty, centred);
195}
196
197
198static uint32_t GetRailContinuationInfo(TileIndex tile)
199{
200 /* Tile offsets and exit dirs for X axis */
203
204 /* Tile offsets and exit dirs for Y axis */
207
208 Axis axis = GetRailStationAxis(tile);
209
210 /* Choose appropriate lookup table to use */
211 const Direction *dir = axis == Axis::X ? x_dir : y_dir;
212 const DiagDirection *diagdir = axis == Axis::X ? x_exits : y_exits;
213
214 uint32_t res = 0;
215 uint i;
216
217 for (i = 0; i < lengthof(x_dir); i++, dir++, diagdir++) {
218 TileIndex neighbour_tile = tile + TileOffsByDir(*dir);
220 if (trackbits.Any()) {
221 /* If there is any track on the tile, set the bit in the second byte */
222 SetBit(res, i + 8);
223
224 /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
225 * with the next tile because the ramp is not going in the right direction. */
226 if (IsTileType(neighbour_tile, TileType::TunnelBridge) && GetTunnelBridgeDirection(neighbour_tile) != *diagdir) {
227 continue;
228 }
229
230 /* If any track reaches our exit direction, set the bit in the lower byte */
231 if (trackbits.Any(DiagdirReachesTracks(*diagdir))) SetBit(res, i);
232 }
233 }
234
235 return res;
236}
237
238
239/* Station Resolver Functions */
240/* virtual */ uint32_t StationScopeResolver::GetRandomBits() const
241{
242 return (this->st == nullptr ? 0 : this->st->random_bits) | (this->tile == INVALID_TILE ? 0 : GetStationTileRandomBits(this->tile) << 16);
243}
244
245
246/* virtual */ uint32_t StationScopeResolver::GetRandomTriggers() const
247{
248 if (this->st == nullptr) return 0;
249
250 StationRandomTriggers triggers = st->waiting_random_triggers;
251
252 auto it = this->st->tile_waiting_random_triggers.find(this->tile);
253 if (it != std::end(this->st->tile_waiting_random_triggers)) triggers.Set(it->second);
254
255 return triggers.base();
256}
257
258
265{
266 if (!this->town_scope.has_value()) {
267 Town *t = nullptr;
268 if (this->station_scope.st != nullptr) {
269 t = this->station_scope.st->town;
270 } else if (this->station_scope.tile != INVALID_TILE) {
271 t = ClosestTownFromTile(this->station_scope.tile, UINT_MAX);
272 }
273 if (t == nullptr) return nullptr;
274 this->town_scope.emplace(*this, t, this->station_scope.st == nullptr);
275 }
276 return &*this->town_scope;
277}
278
279/* virtual */ uint32_t StationScopeResolver::GetVariable(uint8_t variable, [[maybe_unused]] uint32_t parameter, bool &available) const
280{
281 if (this->st == nullptr) {
282 /* Station does not exist, so we're in a purchase list or the land slope check callback. */
283 switch (variable) {
284 case 0x40:
285 case 0x41:
286 case 0x46:
287 case 0x47:
288 case 0x49: return 0x2110000; // Platforms, tracks & position
289 case 0x42: return 0; // Rail type (XXX Get current type from GUI?)
290 case 0x43: return GetCompanyInfo(_current_company); // Station owner
291 case 0x44: return 2; // PBS status
292 case 0x67: // Land info of nearby tile
293 if (this->axis != Axis::Invalid && this->tile != INVALID_TILE) {
294 TileIndex tile = this->tile;
295 if (parameter != 0) tile = GetNearbyTile(parameter, tile, true, this->axis); // only perform if it is required
296
297 Slope tileh = GetTileSlope(tile);
298 bool swap = (this->axis == Axis::Y && HasBit(tileh, to_underlying(Corner::W)) != HasBit(tileh, to_underlying(Corner::E)));
299
300 return GetNearbyTileInformation(tile, this->ro.grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
301 }
302 break;
303
304 case 0x7A: return GetBadgeVariableResult(*this->ro.grffile, this->statspec->badges, parameter);
305
306 case 0xFA: return ClampTo<uint16_t>(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR); // Build date, clamped to a 16 bit value
307 }
308
309 available = false;
310 return UINT_MAX;
311 }
312
313 switch (variable) {
314 /* Calculated station variables */
315 case 0x40:
316 if (!this->cache.v40.has_value()) this->cache.v40 = GetPlatformInfoHelper(this->tile, false, false, false);
317 return *this->cache.v40;
318
319 case 0x41:
320 if (!this->cache.v41.has_value()) this->cache.v41 = GetPlatformInfoHelper(this->tile, true, false, false);
321 return *this->cache.v41;
322
323 case 0x42: return GetTerrainType(this->tile) | (GetReverseRailTypeTranslation(GetRailType(this->tile), this->statspec->grf_prop.grffile) << 8);
324 case 0x43: return GetCompanyInfo(this->st->owner); // Station owner
325 case 0x44: return HasStationReservation(this->tile) ? 7 : 4; // PBS status
326 case 0x45:
327 if (!this->cache.v45.has_value()) this->cache.v45 = GetRailContinuationInfo(this->tile);
328 return *this->cache.v45;
329
330 case 0x46:
331 if (!this->cache.v46.has_value()) this->cache.v46 = GetPlatformInfoHelper(this->tile, false, false, true);
332 return *this->cache.v46;
333
334 case 0x47:
335 if (!this->cache.v47.has_value()) this->cache.v47 = GetPlatformInfoHelper(this->tile, true, false, true);
336 return *this->cache.v47;
337
338 case 0x49:
339 if (!this->cache.v49.has_value()) this->cache.v49 = GetPlatformInfoHelper(this->tile, false, true, false);
340 return *this->cache.v49;
341
342 case 0x4A: // Animation frame of tile
343 return GetAnimationFrame(this->tile);
344
345 /* Variables which use the parameter */
346 /* Variables 0x60 to 0x65 and 0x69 are handled separately below */
347 case 0x66: { // Animation frame of nearby tile
348 TileIndex tile = this->tile;
349 if (parameter != 0) tile = GetNearbyTile(parameter, tile);
350 return this->st->TileBelongsToRailStation(tile) ? GetAnimationFrame(tile) : UINT_MAX;
351 }
352
353 case 0x67: { // Land info of nearby tile
354 Axis axis = GetRailStationAxis(this->tile);
355 TileIndex tile = this->tile;
356 if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
357
358 Slope tileh = GetTileSlope(tile);
359 bool swap = (axis == Axis::Y && HasBit(tileh, to_underlying(Corner::W)) != HasBit(tileh, to_underlying(Corner::E)));
360
361 return GetNearbyTileInformation(tile, this->ro.grffile->grf_version >= 8) ^ (swap ? SLOPE_EW : 0);
362 }
363
364 case 0x68: { // Station info of nearby tiles
365 TileIndex nearby_tile = GetNearbyTile(parameter, this->tile);
366
367 if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
368
369 GrfID grfid = this->st->speclist[GetCustomStationSpecIndex(this->tile)].grfid;
370 bool perpendicular = GetRailStationAxis(this->tile) != GetRailStationAxis(nearby_tile);
371 bool same_station = this->st->TileBelongsToRailStation(nearby_tile);
372 uint32_t res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
373
374 if (IsCustomStationSpecIndex(nearby_tile)) {
375 const auto &sm = BaseStation::GetByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
376 res |= 1 << (sm.grfid != grfid ? 9 : 8) | ClampTo<uint8_t>(sm.localidx);
377 }
378 return res;
379 }
380
381 case 0x6A: { // GRFID of nearby station tiles
382 TileIndex nearby_tile = GetNearbyTile(parameter, this->tile);
383
384 if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
385 if (!IsCustomStationSpecIndex(nearby_tile)) return 0;
386
387 const auto &sm = BaseStation::GetByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
388 return FlattenNewGRFLabel(sm.grfid);
389 }
390
391 case 0x6B: { // 16 bit Station ID of nearby tiles
392 TileIndex nearby_tile = GetNearbyTile(parameter, this->tile);
393
394 if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
395 if (!IsCustomStationSpecIndex(nearby_tile)) return 0xFFFE;
396
397 GrfID grfid = this->st->speclist[GetCustomStationSpecIndex(this->tile)].grfid;
398
399 const auto &sm = BaseStation::GetByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
400 if (sm.grfid == grfid) {
401 return sm.localidx;
402 }
403
404 return 0xFFFE;
405 }
406
407 case 0x7A: return GetBadgeVariableResult(*this->ro.grffile, this->statspec->badges, parameter);
408
409 /* General station variables */
410 case 0x82: return 50;
411 case 0x84: return this->st->string_id.base();
412 case 0x86: return 0;
413 case 0xF0: return this->st->facilities.base();
414 case 0xFA: return ClampTo<uint16_t>(this->st->build_date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR);
415 }
416
417 return this->st->GetNewGRFVariable(this->ro, variable, parameter, available);
418}
419
420uint32_t Station::GetNewGRFVariable(const ResolverObject &object, uint8_t variable, uint8_t parameter, bool &available) const
421{
422 switch (variable) {
423 case 0x48: { // Accepted cargo types
424 uint32_t value = GetAcceptanceMask(this).base();
425 return value;
426 }
427
428 case 0x8A: return this->had_vehicle_of_type.base();
429 case 0xF1: return !this->airport.IsEmpty() ? this->airport.GetSpec()->ttd_airport_type : ATP_TTDP_LARGE;
430 case 0xF2: return (this->truck_stops != nullptr) ? this->truck_stops->status.base() : 0;
431 case 0xF3: return (this->bus_stops != nullptr) ? this->bus_stops->status.base() : 0;
432 case 0xF6: return this->airport.blocks.base();
433 case 0xF7: return GB(this->airport.blocks.base(), 8, 8);
434 }
435
436 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69 */
437 if ((variable >= 0x60 && variable <= 0x65) || variable == 0x69) {
438 CargoType cargo = GetCargoTranslation(parameter, object.grffile);
439
440 if (!IsValidCargoType(cargo)) {
441 switch (variable) {
442 case 0x62: return 0xFFFFFFFF;
443 case 0x64: return 0xFF00;
444 default: return 0;
445 }
446 }
447 const GoodsEntry *ge = &this->goods[cargo];
448
449 switch (variable) {
450 case 0x60: return std::min(ge->TotalCount(), 4095u);
451 case 0x61: return ge->HasVehicleEverTriedLoading() ? ge->time_since_pickup : 0;
452 case 0x62: return ge->HasRating() ? ge->rating : 0xFFFFFFFF;
453 case 0x63: return ge->HasData() ? ge->GetData().cargo.PeriodsInTransit() : 0;
454 case 0x64: return ge->HasVehicleEverTriedLoading() ? ge->last_speed | (ge->last_age << 8) : 0xFF00;
455 case 0x65: return ge->status.Test(GoodsEntry::State::Acceptance) ? (1U << 3) : 0;
456 case 0x69: return ge->ConvertState();
457 }
458 }
459
460 /* Handle cargo variables (deprecated) */
461 if (variable >= 0x8C && variable <= 0xEC) {
462 const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
463 switch (GB(variable - 0x8C, 0, 3)) {
464 case 0: return g->TotalCount();
465 case 1: return GB(std::min(g->TotalCount(), 4095u), 0, 4) | (g->status.Test(GoodsEntry::State::Acceptance) ? (1U << 7) : 0);
466 case 2: return g->time_since_pickup;
467 case 3: return g->rating;
468 case 4: return (g->HasData() ? g->GetData().cargo.GetFirstStation() : StationID::Invalid()).base();
469 case 5: return g->HasData() ? g->GetData().cargo.PeriodsInTransit() : 0;
470 case 6: return g->last_speed;
471 case 7: return g->last_age;
472 }
473 }
474
475 object.UnhandledVariable(variable);
476
477 available = false;
478 return UINT_MAX;
479}
480
481uint32_t Waypoint::GetNewGRFVariable(const ResolverObject &ro, uint8_t variable, [[maybe_unused]] uint8_t parameter, bool &available) const
482{
483 switch (variable) {
484 case 0x48: return 0; // Accepted cargo types
485 case 0x8A: return StationVehicleTypes{StationVehicleType::Waypoint}.base();
486 case 0xF1: return 0; // airport type
487 case 0xF2: return 0; // truck stop status
488 case 0xF3: return 0; // bus stop status
489 case 0xF6: return 0; // airport flags
490 case 0xF7: return 0; // airport flags cont.
491 }
492
493 /* Handle cargo variables with parameter, 0x60 to 0x65 and 0x69. */
494 if ((variable >= 0x60 && variable <= 0x65) || variable == 0x69) {
495 return 0;
496 }
497
498 /* Handle cargo variables (deprecated) */
499 if (variable >= 0x8C && variable <= 0xEC) {
500 switch (GB(variable - 0x8C, 0, 3)) {
501 case 3: return INITIAL_STATION_RATING;
502 case 4: return StationID::Invalid().base();
503 default: return 0;
504 }
505 }
506
507 ro.UnhandledVariable(variable);
508
509 available = false;
510 return UINT_MAX;
511}
512
513/* virtual */ const SpriteGroup *StationResolverObject::ResolveReal(const RealSpriteGroup &group) const
514{
515 if (this->station_scope.st == nullptr || !Station::IsExpected(this->station_scope.st)) {
516 if (!group.loading.empty()) return group.loading[0];
517 return nullptr;
518 }
519
520 uint cargo = 0;
521 const Station *st = Station::From(this->station_scope.st);
522
523 switch (this->station_scope.cargo_type) {
524 case INVALID_CARGO:
527 cargo = 0;
528 break;
529
531 for (const GoodsEntry &ge : st->goods) {
532 cargo += ge.TotalCount();
533 }
534 break;
535
536 default: {
537 const GoodsEntry &ge = st->goods[this->station_scope.cargo_type];
538 cargo = ge.TotalCount();
539 break;
540 }
541 }
542
543 if (this->station_scope.statspec->flags.Test(StationSpecFlag::DivByStationArea)) {
544 uint area = 0;
545 for (const TileIndex &tile : st->train_station) {
546 if (st->TileBelongsToRailStation(tile)) ++area;
547 }
548 cargo /= area;
549 } else if (this->station_scope.statspec->flags.Test(StationSpecFlag::DivByStationSize)) {
550 cargo /= (st->train_station.w + st->train_station.h); // Old code that uses half of the perimeter as the station size, compatible with TTDPatch.
551 }
552 cargo = std::min(0xfffu, cargo);
553
554 if (cargo > this->station_scope.statspec->cargo_threshold) {
555 if (!group.loading.empty()) {
556 uint set = ((cargo - this->station_scope.statspec->cargo_threshold) * static_cast<uint>(group.loading.size())) / (4096 - this->station_scope.statspec->cargo_threshold);
557 return group.loading[set];
558 }
559 } else {
560 if (!group.loaded.empty()) {
561 uint set = (cargo * static_cast<uint>(group.loaded.size())) / (this->station_scope.statspec->cargo_threshold + 1);
562 return group.loaded[set];
563 }
564 }
565
566 if (!group.loading.empty()) return group.loading[0];
567 return nullptr;
568}
569
574
576{
577 return this->station_scope.statspec->grf_prop.local_id;
578}
579
592 station_scope(*this, statspec, base_station, tile)
593{
595
596 if (this->station_scope.st == nullptr) {
597 /* No station, so we are in a purchase list */
598 ctype = CargoGRFFileProps::SG_PURCHASE;
599 } else if (Station::IsExpected(this->station_scope.st)) {
600 const Station *st = Station::From(this->station_scope.st);
601 /* Pick the first cargo that we have waiting */
602 for (const auto &[cargo, spritegroup] : statspec->grf_prop.spritegroups) {
603 if (cargo < NUM_CARGO && st->goods[cargo].TotalCount() > 0) {
604 ctype = static_cast<CargoType>(cargo);
605 break;
606 }
607 }
608 }
609
610 this->root_spritegroup = this->station_scope.statspec->grf_prop.GetSpriteGroup(ctype);
611 if (this->root_spritegroup == nullptr) {
613 this->root_spritegroup = this->station_scope.statspec->grf_prop.GetSpriteGroup(ctype);
614 }
615
616 /* Remember the cargo type we've picked */
617 this->station_scope.cargo_type = ctype;
618}
619
628SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
629{
630 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, var10);
631 const auto *group = object.Resolve<ResultSpriteGroup>();
632
633 /* A zero-length ResultSpriteGroup is valid because the output value is an offset, not a sprite ID within the ResultSpriteGroup. */
634 if (group == nullptr) return 0;
635 return group->sprite - SPR_RAIL_PLATFORM_Y_FRONT;
636}
637
638void GetCustomStationRelocation(SpriteLayoutProcessor &processor, const StationSpec *statspec, BaseStation *st, TileIndex tile)
639{
640 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK);
641 for (uint8_t var10 : processor.Var10Values()) {
642 object.callback_param1 = var10;
643 const auto *group = object.Resolve<ResultSpriteGroup>();
644
645 /* ProcessRegisters must be called no matter the type of the sprite resolve result or whether it is valid.
646 * The sprite offset is only used for layouts with the SPRITE_MODIFIER_CUSTOM_SPRITE flag, however other aspects of layouts
647 * such as register operations must still be processed even if this flag is not set and the sprite offset is never used.
648 * A zero-length ResultSpriteGroup is valid because the output value is an offset, not a sprite ID within the ResultSpriteGroup. */
649 processor.ProcessRegisters(object, var10, group != nullptr ? group->sprite - SPR_RAIL_PLATFORM_Y_FRONT : 0);
650 }
651}
652
662SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
663{
664 /* callback_param1 == 2 means we are resolving the foundation sprites. */
665 StationResolverObject object(statspec, st, tile, CBID_NO_CALLBACK, 2, layout | (edge_info << 16));
666
667 const auto *group = object.Resolve<ResultSpriteGroup>();
668 /* Note: SpriteGroup::Resolve zeroes all registers, so register 0x100 is initialised to 0. (compatibility) */
669 uint32_t offset = static_cast<uint32_t>(object.GetRegister(0x100));
670 if (group == nullptr || group->num_sprites <= offset) return 0;
671
672 return group->sprite + offset;
673}
674
675
676uint16_t GetStationCallback(CallbackID callback, uint32_t param1, uint32_t param2, const StationSpec *statspec, BaseStation *st, TileIndex tile, std::span<int32_t> regs100)
677{
678 StationResolverObject object(statspec, st, tile, callback, param1, param2);
679 return object.ResolveCallback(regs100);
680}
681
692CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, uint8_t plat_len, uint8_t numtracks)
693{
694 TileIndex diff = cur_tile - north_tile;
695 Slope slope = GetTileSlope(cur_tile);
696
697 StationResolverObject object(statspec, nullptr, cur_tile, CBID_STATION_LAND_SLOPE_CHECK,
698 (slope << 4) | (slope ^ (axis == Axis::Y && HasBit(slope, to_underlying(Corner::W)) != HasBit(slope, to_underlying(Corner::E)) ? SLOPE_EW : 0)),
699 (numtracks << 24) | (plat_len << 16) | (axis == Axis::Y ? TileX(diff) << 8 | TileY(diff) : TileY(diff) << 8 | TileX(diff)));
700 object.station_scope.axis = axis;
701
702 std::array<int32_t, 16> regs100;
703 uint16_t cb_res = object.ResolveCallback(regs100);
704
705 /* Failed callback means success. */
706 if (cb_res == CALLBACK_FAILED) return CommandCost();
707
708 /* The meaning of bit 10 is inverted for a grf version < 8. */
709 if (statspec->grf_prop.grffile->grf_version < 8) ToggleBit(cb_res, 10);
710 return GetErrorMessageFromLocationCallbackResult(cb_res, regs100, statspec->grf_prop.grffile, STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
711}
712
713
720std::optional<uint8_t> AllocateSpecToStation(const StationSpec *spec, BaseStation *st)
721{
722 uint i;
723
724 if (spec == nullptr) return 0;
725
726 /* If station doesn't exist yet then the first slot is available. */
727 if (st == nullptr) return 1;
728
729 for (i = 1; i < st->speclist.size() && i < NUM_STATIONSSPECS_PER_STATION; i++) {
730 if (st->speclist[i].spec == nullptr && st->speclist[i].grfid.Empty()) break;
731 }
732
734 /* As final effort when the spec list is already full...
735 * try to find the same spec and return that one. This might
736 * result in slightly "wrong" (as per specs) looking stations,
737 * but it's fairly unlikely that one reaches the limit anyways.
738 */
739 for (i = 1; i < st->speclist.size() && i < NUM_STATIONSSPECS_PER_STATION; i++) {
740 if (st->speclist[i].spec == spec) return i;
741 }
742
743 return std::nullopt;
744 }
745
746 return i;
747}
748
755void AssignSpecToStation(const StationSpec *spec, BaseStation *st, uint8_t specindex)
756{
757 if (specindex == 0) return;
758 if (specindex >= st->speclist.size()) st->speclist.resize(specindex + 1);
759
760 st->speclist[specindex].spec = spec;
761 st->speclist[specindex].grfid = spec->grf_prop.grfid;
762 st->speclist[specindex].localidx = spec->grf_prop.local_id;
763
765}
766
772void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
773{
774 /* specindex of 0 (default) is never freeable */
775 if (specindex == 0) return;
776
777 /* Check all tiles over the station to check if the specindex is still in use */
779 if (st->TileBelongsToRailStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
780 return;
781 }
782 }
783
784 /* This specindex is no longer in use, so deallocate it */
785 st->speclist[specindex].spec = nullptr;
786 st->speclist[specindex].grfid = {};
787 st->speclist[specindex].localidx = 0;
788
789 /* If this was the highest spec index, reallocate */
790 if (specindex == st->speclist.size() - 1) {
791 size_t num_specs;
792 for (num_specs = st->speclist.size() - 1; num_specs > 0; num_specs--) {
793 if (!st->speclist[num_specs].grfid.Empty()) break;
794 }
795
796 if (num_specs > 0) {
797 st->speclist.resize(num_specs + 1);
798 } else {
799 st->speclist.clear();
800 st->cached_anim_triggers = {};
802 return;
803 }
804 }
805
807}
808
819bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
820{
821 const DrawTileSprites *sprites = nullptr;
822 const RailTypeInfo *rti = GetRailTypeInfo(railtype);
824 uint tile = 2;
825
826 const StationSpec *statspec = StationClass::Get(sclass)->GetSpec(station);
827 if (statspec == nullptr) return false;
828
830 uint16_t callback = GetStationCallback(CBID_STATION_DRAW_TILE_LAYOUT, 0, 0, statspec, nullptr, INVALID_TILE);
831 if (callback != CALLBACK_FAILED) tile = callback & ~1;
832 }
833
834 uint32_t total_offset = rti->GetRailtypeSpriteOffset();
835 uint32_t relocation = 0;
836 uint32_t ground_relocation = 0;
837 const NewGRFSpriteLayout *layout = nullptr;
838 SpriteLayoutProcessor processor; // owns heap, borrowed by tmp_rail_layout and sprites
839 DrawTileSpriteSpan tmp_rail_layout;
840
841 if (statspec->renderdata.empty()) {
843 } else {
844 layout = &statspec->renderdata[(tile < statspec->renderdata.size()) ? tile + to_underlying(axis) : to_underlying(axis)];
845 if (!layout->NeedsPreprocessing()) {
846 sprites = layout;
847 layout = nullptr;
848 }
849 }
850
851 if (layout != nullptr) {
852 /* Sprite layout which needs preprocessing */
853 bool separate_ground = statspec->flags.Test(StationSpecFlag::SeparateGround);
854 processor = SpriteLayoutProcessor(*layout, total_offset, rti->fallback_railtype, 0, 0, separate_ground);
855 GetCustomStationRelocation(processor, statspec, nullptr, INVALID_TILE);
856 tmp_rail_layout = processor.GetLayout();
857 sprites = &tmp_rail_layout;
858 total_offset = 0;
859 } else {
860 /* Simple sprite layout */
861 ground_relocation = relocation = GetCustomStationRelocation(statspec, nullptr, INVALID_TILE, 0);
863 ground_relocation = GetCustomStationRelocation(statspec, nullptr, INVALID_TILE, 1);
864 }
865 ground_relocation += rti->fallback_railtype;
866 }
867
868 SpriteID image = sprites->ground.sprite;
869 PaletteID pal = sprites->ground.pal;
870 RailTrackOffset overlay_offset;
871 if (rti->UsesOverlay() && SplitGroundSpriteForOverlay(nullptr, &image, &overlay_offset)) {
873 DrawSprite(image, PAL_NONE, x, y);
874 DrawSprite(ground + overlay_offset, PAL_NONE, x, y);
875 } else {
876 image += HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE) ? ground_relocation : total_offset;
877 if (HasBit(pal, SPRITE_MODIFIER_CUSTOM_SPRITE)) pal += ground_relocation;
878 DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
879 }
880
881 DrawRailTileSeqInGUI(x, y, sprites, total_offset, relocation, palette);
882
883 return true;
884}
885
886
887const StationSpec *GetStationSpec(TileIndex t)
888{
889 if (!IsCustomStationSpecIndex(t)) return nullptr;
890
891 const BaseStation *st = BaseStation::GetByTile(t);
892 uint specindex = GetCustomStationSpecIndex(t);
893 return specindex < st->speclist.size() ? st->speclist[specindex].spec : nullptr;
894}
895
906uint16_t GetAnimStationCallback(CallbackID callback, uint32_t param1, uint32_t param2, const StationSpec *statspec, BaseStation *st, TileIndex tile, int)
907{
908 return GetStationCallback(callback, param1, param2, statspec, st, tile);
909}
910
919
920void AnimateStationTile(TileIndex tile)
921{
922 const StationSpec *ss = GetStationSpec(tile);
923 if (ss == nullptr) return;
924
926}
927
928void TriggerStationAnimation(BaseStation *st, TileIndex trigger_tile, StationAnimationTrigger trigger, CargoType cargo_type)
929{
930 /* List of coverage areas for each animation trigger */
932 TriggerArea::Tile, // Built
933 TriggerArea::Whole, // NewCargo
934 TriggerArea::Whole, // CargoTaken
935 TriggerArea::Platform, // VehicleArrives
936 TriggerArea::Platform, // VehicleDeparts
937 TriggerArea::Platform, // VehicleLoads
938 TriggerArea::Whole, // AcceptanceTick
939 TriggerArea::Tile, // TileLoop
940 TriggerArea::Platform, // PathReservation
941 };
942
943 assert(st != nullptr);
944
945 /* Check the cached animation trigger bitmask to see if we need
946 * to bother with any further processing. */
947 if (!st->cached_anim_triggers.Test(trigger)) return;
948
949 uint16_t random_bits = Random();
950
951 /* Check all tiles over the station to check if the specindex is still in use */
952 for (TileIndex tile : GetRailTileArea(st, trigger_tile, tas[trigger])) {
953 if (st->TileBelongsToRailStation(tile)) {
954 const StationSpec *ss = GetStationSpec(tile);
955 if (ss != nullptr && ss->animation.triggers.Test(trigger)) {
956 uint8_t var18_extra = 0;
957 if (IsValidCargoType(cargo_type)) {
958 var18_extra |= ss->grf_prop.grffile->cargo_map[cargo_type] << 8;
959 }
960 StationAnimationBase::ChangeAnimationFrame(CBID_STATION_ANIMATION_TRIGGER, ss, st, tile, (random_bits << 16) | GB(Random(), 0, 16), to_underlying(trigger) | var18_extra);
961 }
962 }
963 }
964}
965
974{
975 /* List of coverage areas for each animation trigger */
978 };
979
980 assert(st != nullptr);
981
982 /* Check the cached cargo trigger bitmask to see if we need
983 * to bother with any further processing.
984 * Note: cached_cargo_triggers must be non-zero even for cargo-independent triggers. */
985 if (st->cached_cargo_triggers.None()) return;
986 if (IsValidCargoType(cargo_type) && !st->cached_cargo_triggers.Test(cargo_type)) return;
987
988 uint32_t whole_reseed = 0;
989
990 CargoTypes cargo_waiting{};
991 if (trigger == StationRandomTrigger::CargoTaken) {
992 cargo_waiting = GetCargoWaitingMask(Station::From(st));
993 }
994
995 /* Store triggers now for var 5F */
996 TriggerArea ta = tas[trigger];
997 if (ta == TriggerArea::Whole) st->waiting_random_triggers.Set(trigger);
998 StationRandomTriggers used_random_triggers;
999
1000 /* Check all tiles over the station to check if the specindex is still in use */
1001 for (TileIndex tile : GetRailTileArea(st, trigger_tile, ta)) {
1002 if (st->TileBelongsToRailStation(tile)) {
1003 /* Store triggers now for var 5F */
1004 st->tile_waiting_random_triggers[tile].Set(trigger);
1005
1006 const StationSpec *ss = GetStationSpec(tile);
1007 if (ss == nullptr) continue;
1008
1009 /* Cargo taken "will only be triggered if all of those
1010 * cargo types have no more cargo waiting." */
1011 if (trigger == StationRandomTrigger::CargoTaken) {
1012 if (ss->cargo_triggers.Any(cargo_waiting)) continue;
1013 }
1014
1015 if (!IsValidCargoType(cargo_type) || ss->cargo_triggers.Test(cargo_type)) {
1016 StationResolverObject object(ss, st, tile, CBID_RANDOM_TRIGGER, 0);
1017 object.SetWaitingRandomTriggers(st->waiting_random_triggers | st->tile_waiting_random_triggers[tile]);
1018
1019 object.ResolveRerandomisation();
1020
1021 st->tile_waiting_random_triggers[tile].Reset(object.GetUsedRandomTriggers());
1022 used_random_triggers.Set(object.GetUsedRandomTriggers());
1023
1024 uint32_t reseed = object.GetReseedSum();
1025 if (reseed != 0) {
1026 whole_reseed |= reseed;
1027 reseed >>= 16;
1028
1029 /* Set individual tile random bits */
1030 uint8_t random_bits = GetStationTileRandomBits(tile);
1031 random_bits &= ~reseed;
1032 random_bits |= Random() & reseed;
1033 SetStationTileRandomBits(tile, random_bits);
1034
1035 MarkTileDirtyByTile(tile);
1036 }
1037 }
1038 }
1039 }
1040
1041 /* Update whole station random bits */
1042 st->waiting_random_triggers.Reset(used_random_triggers);
1043 if ((whole_reseed & 0xFFFF) != 0) {
1044 st->random_bits &= ~whole_reseed;
1045 st->random_bits |= Random() & whole_reseed;
1046 }
1047}
1048
1054{
1055 st->cached_anim_triggers = {};
1057
1058 /* Combine animation trigger bitmask for all station specs
1059 * of this station. */
1060 for (const auto &sm : GetStationSpecList<StationSpec>(st)) {
1061 if (sm.spec == nullptr) continue;
1062 st->cached_anim_triggers.Set(sm.spec->animation.triggers);
1063 st->cached_cargo_triggers.Set(sm.spec->cargo_triggers);
1064 }
1065}
1066
std::vector< SpecMapping< T > > & GetStationSpecList(BaseStation *bst)
Get spec mapping list for each supported custom spec type.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T ToggleBit(T &x, const uint8_t y)
Toggles a bit in a variable.
static constexpr CargoType INVALID_CARGO
Invalid marker for cargoes.
Definition cargo_type.h:83
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
uint PeriodsInTransit() const
Returns average number of cargo aging periods in transit for a cargo entity.
Common return value for all commands.
Struct containing information relating to NewGRF classes for stations and airports.
const Tspec * GetSpec(uint index) const
Get a spec from the class at a given index.
void Insert(Tspec *spec)
Insert a spec into the class, and update its index.
static NewGRFClass * Get(StationClassID class_index)
StringID name
Name of this class.
static StationClassID Allocate(GlobalID global_id)
uint16_t w
The width of the area.
uint16_t h
The height of the area.
This struct contains all the info that is needed to draw and construct tracks.
Definition rail.h:134
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition rail.h:209
uint GetRailtypeSpriteOffset() const
Offset between the current railtype and normal rail.
Definition rail.h:306
Add dynamic register values to a sprite layout.
DrawTileSpriteSpan GetLayout() const
Returns the result spritelayout after preprocessing.
void ProcessRegisters(const struct ResolverObject &object, uint8_t resolved_var10, uint32_t resolved_sprite)
Evaluates the register modifiers and integrates them into the preprocessed sprite layout.
SetBitIterator< uint8_t, uint32_t > Var10Values() const
Get values for variable 10 to resolve sprites for.
StationID GetFirstStation() const
Returns first station of the first cargo packet in this list.
static Date date
Current date in days (day counter).
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
Functions related to debugging.
Direction
Defines the 8 directions on the map.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast.
@ SE
Southeast.
Axis
Enumeration for the two axis X and Y.
@ X
The X axis.
@ Invalid
Flag for an invalid Axis.
@ Y
The y axis.
DiagDirection
Enumeration for diagonal directions.
@ SW
Southwest.
@ NW
Northwest.
@ NE
Northeast, upper right on your monitor.
@ SE
Southeast.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static const SpriteID SPR_RAIL_PLATFORM_Y_FRONT
Definition sprites.h:465
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
TileIndexDiff TileOffsByAxis(Axis axis)
Convert an Axis to a TileIndexDiff.
Definition map_func.h:559
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
constexpr TileIndex TileAdd(TileIndex tile, TileIndexDiff offset)
Adds a given offset to a tile.
Definition map_func.h:461
TileIndexDiff TileOffsByDir(Direction dir)
Convert a Direction to a TileIndexDiff.
Definition map_func.h:588
int32_t TileIndexDiff
An offset value between two tiles.
Definition map_type.h:23
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
constexpr uint32_t FlattenNewGRFLabel(T label)
Flatten a NewGRF related label to a 32 bits integer.
Definition newgrf.h:262
GrfSpecFeature
Definition newgrf.h:81
@ Stations
Stations feature.
Definition newgrf.h:86
@ ATP_TTDP_LARGE
Same as AT_LARGE.
Function implementations related to NewGRF animation.
uint32_t GetBadgeVariableResult(const GRFFile &grffile, std::span< const BadgeID > badges, uint32_t parameter)
Test for a matching badge in a list of badges, returning the number of matching bits.
Functions related to NewGRF badges.
StationCallbackMask
Callback masks for stations.
@ DrawTileLayout
Use callback to select a tile layout to use when drawing.
@ AnimationNextFrame
Use a custom next frame callback.
@ AnimationSpeed
Customize the animation speed of the station.
CallbackID
List of implemented NewGRF callbacks.
@ CBID_STATION_ANIMATION_TRIGGER
Called for periodically starting or stopping the animation.
@ CBID_STATION_DRAW_TILE_LAYOUT
Choose a tile layout to draw, instead of the standard range.
@ CBID_NO_CALLBACK
Set when using the callback resolve system, but not to resolve a callback.
@ CBID_STATION_ANIMATION_NEXT_FRAME
Called to determine station tile next animation frame.
@ CBID_STATION_ANIMATION_SPEED
Called to indicate how long the current animation frame should last.
@ CBID_RANDOM_TRIGGER
Set when calling a randomizing trigger (almost undocumented).
@ CBID_STATION_LAND_SLOPE_CHECK
Callback done for each tile of a station to check the slope.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
CargoType GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoType.
Cargo support for NewGRFs.
Implementation of the NewGRF class' functions.
CommandCost GetErrorMessageFromLocationCallbackResult(uint16_t cb_res, std::span< const int32_t > textstack, const GRFFile *grffile, StringID default_error)
Get the error message from a shape/location/slope check callback result.
uint32_t GetCompanyInfo(CompanyID owner, const Livery *l)
Returns company information like in vehicle var 43 or station var 43.
uint32_t GetNearbyTileInformation(TileIndex tile, bool grf_version8)
Common part of station var 0x67, house var 0x62, indtile var 0x60, industry var 0x62,...
uint32_t GetTerrainType(TileIndex tile, TileContext context)
Function used by houses (and soon industries) to get information on type of "terrain" the tile it is ...
TileIndex GetNearbyTile(uint8_t parameter, TileIndex tile, bool signed_offsets, Axis axis)
Get the tile at the given offset.
uint8_t GetReverseRailTypeTranslation(RailType railtype, const GRFFile *grffile)
Perform a reverse railtype lookup to get the GRF internal ID.
SpriteID GetCustomRailSprite(const RailTypeInfo *rti, TileIndex tile, RailSpriteType rtsg, TileContext context, uint *num_results)
Get the sprite to draw for the given tile.
NewGRF handling of rail types.
Action 2 handling.
static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
Find the end of a railway station, from the tile, in the direction of delta.
SpriteID GetCustomStationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint32_t var10)
Resolve sprites for drawing a station tile.
static TileArea GetRailTileArea(const BaseStation *st, TileIndex tile, TriggerArea ta)
Get the tile area of a rail station with trigger area type.
SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, BaseStation *st, TileIndex tile, uint layout, uint edge_info)
Resolve the sprites for custom station foundations.
void StationUpdateCachedTriggers(BaseStation *st)
Update the cached animation trigger bitmask for a station.
bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
Draw representation of a station tile for GUI purposes.
void AssignSpecToStation(const StationSpec *spec, BaseStation *st, uint8_t specindex)
Assign a previously allocated StationSpec specindex to a Station.
void DeallocateSpecFromStation(BaseStation *st, uint8_t specindex)
Deallocate a StationSpec from a Station.
void TriggerStationRandomisation(BaseStation *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoType cargo_type)
Trigger station randomisation.
static const uint NUM_STATIONSSPECS_PER_STATION
Maximum number of parts per station.
CommandCost PerformStationTileSlopeCheck(TileIndex north_tile, TileIndex cur_tile, const StationSpec *statspec, Axis axis, uint8_t plat_len, uint8_t numtracks)
Check the slope of a tile of a new station.
uint32_t GetPlatformInfo(StationGfx gfx, int platforms, int length, int platform, int position, bool centred)
Evaluate a tile's position within a station, and return the result in a bit-stuffed format.
uint16_t GetAnimStationCallback(CallbackID callback, uint32_t param1, uint32_t param2, const StationSpec *statspec, BaseStation *st, TileIndex tile, int)
Perform the station callback in the context of the AnimationBase callback.
std::optional< uint8_t > AllocateSpecToStation(const StationSpec *spec, BaseStation *st)
Allocate a StationSpec to a Station.
Header file for NewGRF stations.
@ Cb141RandomBits
Callback 141 needs random bits.
@ DivByStationArea
Divide cargo amount by station area.
@ SeparateGround
Use different sprite set for ground sprites.
@ DivByStationSize
Divide cargo amount by station size (perimeter).
PoolID< uint16_t, struct StationClassIDTag, UINT16_MAX, UINT16_MAX > StationClassID
Class IDs for stations.
static const StationClass::GlobalID STATION_CLASS_LABEL_DEFAULT
Class label for default rail station.
static const StationClass::GlobalID STATION_CLASS_LABEL_WAYPOINT
Class label for default rail waypoints.
Functions to handle the town part of NewGRF towns.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
@ Ground
Main group of ground images.
Definition rail.h:45
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:320
RailTrackOffset
Offsets for sprites within an overlay/underlay set.
Definition rail.h:63
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:26
@ Invalid
Invalid marker.
Definition road_type.h:42
Base class for roadstops.
A number of safeguards to prevent using unsafe methods.
@ E
East tile corner.
Definition slope_type.h:24
@ W
West tile corner.
Definition slope_type.h:22
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_EW
east and west corner are raised
Definition slope_type.h:64
void DrawRailTileSeqInGUI(int x, int y, const DrawTileSprites *dts, int32_t total_offset, uint32_t newgrf_offset, PaletteID default_palette)
Draw tile sprite sequence in GUI with railroad specifics.
Definition sprite.h:122
PaletteID GroundSpritePaletteTransform(SpriteID image, PaletteID pal, PaletteID default_pal)
Applies PALETTE_MODIFIER_COLOUR to a palette entry of a ground sprite.
Definition sprite.h:207
static constexpr uint8_t SPRITE_MODIFIER_CUSTOM_SPRITE
these masks change the colours of the palette for a sprite.
Definition sprites.h:1732
Base classes/functions for stations.
const DrawTileSprites * GetStationTileLayout(StationType st, uint8_t gfx)
Get station tile layout for a station type and its station gfx.
CargoTypes GetAcceptanceMask(const Station *st)
Get a mask of the cargo types that the station accepts.
CargoTypes GetCargoWaitingMask(const Station *st)
Get a mask of the cargo types that have cargo waiting at the station.
bool SplitGroundSpriteForOverlay(const TileInfo *ti, SpriteID *ground, RailTrackOffset *overlay_offset)
Check whether a sprite is a track sprite, which can be replaced by a non-track ground sprite and a ra...
Functions related to stations.
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:66
bool IsCompatibleTrainStationTile(Tile test_tile, Tile station_tile)
Check if a tile is a valid continuation to a railstation tile.
uint8_t GetStationTileRandomBits(Tile t)
Get the random bits of a station tile.
bool IsRailStationTile(Tile t)
Is this tile a station tile and a rail station?
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition station_map.h:26
bool HasStationTileRail(Tile t)
Has this station tile a rail?
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
void SetStationTileRandomBits(Tile t, uint8_t random_bits)
Set the random bits for a station tile.
Axis GetRailStationAxis(Tile t)
Get the rail direction of a rail station.
uint8_t StationGfx
Index of station graphics.
Definition station_map.h:18
bool IsCustomStationSpecIndex(Tile t)
Is there a custom rail station spec on this tile?
bool HasStationRail(Tile t)
Has this station tile a rail?
bool HasStationReservation(Tile t)
Get the reservation state of the rail station.
TriggerArea
Scope of station/roadstop animation or randomisation trigger.
@ Platform
Trigger a single platform.
@ Tile
Trigger an individual tile.
@ Whole
Trigger the entire station.
EnumBitSet< StationRandomTrigger, uint8_t > StationRandomTriggers
Bitset of StationRandomTrigger elements.
@ Rail
Railways/train station.
@ RailWaypoint
Waypoint for trains.
StationRandomTrigger
Randomisation triggers for stations and roadstops.
@ CargoTaken
Trigger station when cargo is completely taken.
StationAnimationTrigger
Animation triggers for stations and roadstops.
EnumBitSet< StationVehicleType, uint8_t > StationVehicleTypes
Bitset of StationVehicleType elements.
@ Waypoint
Station is a waypoint (Save load conversion and NewGRF only!).
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
Helper class for a unified approach to NewGRF animation.
static void ChangeAnimationFrame(CallbackID cb, const StationSpec *spec, BaseStation *obj, TileIndex tile, uint32_t random_bits, uint32_t trigger, int extra_data={})
static void AnimateTile(const StationSpec *spec, BaseStation *obj, TileIndex tile, bool random_animation, int extra_data={})
Base class for all station-ish types.
std::vector< SpecMapping< StationSpec > > speclist
List of rail station specs of this station.
virtual TileArea GetTileArea(StationType type) const =0
Get the tile area for a given station type.
TileArea train_station
Tile area the train 'station' part covers.
StationAnimationTriggers cached_anim_triggers
NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
virtual bool TileBelongsToRailStation(TileIndex tile) const =0
Check whether a specific tile belongs to this station.
uint16_t random_bits
Random bits assigned to this station.
StationRandomTriggers waiting_random_triggers
Waiting triggers (NewGRF), shared by all station parts/tiles, road stops, ... essentially useless and...
CargoTypes cached_cargo_triggers
NOSAVE: Combined cargo trigger bitmask.
static constexpr CargoType SG_PURCHASE
Used in purchase lists before an item exists.
static constexpr CargoType SG_DEFAULT
Default type used when no more-specific cargo matches.
static constexpr CargoType SG_DEFAULT_NA
Used only by stations and roads when no more-specific cargo matches.
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:76
Ground palette sprite of a tile, together with its sprite layout.
Definition sprite.h:55
PalSpriteID ground
Palette and sprite for the ground.
Definition sprite.h:56
GrfID grfid
grfid that introduced this entity.
const struct GRFFile * grffile
grf file that introduced this entity
uint16_t local_id
id defined by the grf file for this entity
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoType -> local ID).
Definition newgrf.h:148
uint8_t grf_version
GRF version (See https://newgrf-specs.tt-wiki.net/wiki/Version_numbers#GRF_version).
Definition newgrf.h:129
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Stores station stats for a single cargo.
bool HasRating() const
Does this cargo have a rating at this station?
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
States status
Status of this cargo, see State.
@ LastMonth
Set when cargo was delivered for final delivery last month.
@ Acceptance
Set when the station accepts the cargo currently for final deliveries.
@ EverAccepted
Set when a vehicle ever delivered cargo to the station for final delivery.
@ AcceptedBigtick
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
@ CurrentMonth
Set when cargo was delivered for final delivery this month.
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
bool HasVehicleEverTriedLoading() const
Reports whether a vehicle has ever tried to load the cargo at this station.
uint8_t rating
Station rating for this cargo.
bool HasData() const
Test if this goods entry has optional cargo packet/flow data.
uint8_t ConvertState() const
Convert GoodsEntry status to the form required for NewGRF variables.
NewGRF supplied spritelayout.
bool NeedsPreprocessing() const
Tests whether this spritelayout needs preprocessing by SpriteLayoutProcessor, or whether it can be us...
SpriteID sprite
The 'real' sprite.
Definition gfx_type.h:23
PaletteID pal
The palette (use PAL_NONE) if not needed).
Definition gfx_type.h:24
'Real' sprite groups contain a list of other result or callback sprite groups.
std::vector< const SpriteGroup * > loaded
List of loaded groups (can be SpriteIDs or Callback results).
std::vector< const SpriteGroup * > loading
List of loading groups (can be SpriteIDs or Callback results).
Interface for SpriteGroup-s to access the gamestate.
const GRFFile * grffile
GRFFile the resolved SpriteGroup belongs to.
uint32_t callback_param2
Second parameter (var 18) of the callback.
void UnhandledVariable(uint8_t variable) const
Log a message for an unhandled NewGRF variable.
CallbackID callback
Callback being resolved.
uint32_t callback_param1
First parameter (var 10) of the callback.
A result sprite group returns the first SpriteID and the number of sprites in the set.
ResolverObject & ro
Surrounding resolver object.
Specialization of ResolverObject with type-safe access to RandomTriggers.
static bool IsExpected(const BaseStation *st)
static Station * From(BaseStation *st)
Common wrapper for all the different sprite group types.
Helper class for animation control.
Station resolver.
StationScopeResolver station_scope
The station scope resolver.
uint32_t GetDebugID() const override
Get an identifier for the item being resolved.
TownScopeResolver * GetTown()
Get the town scope associated with a station, if it exists.
std::optional< TownScopeResolver > town_scope
The town scope resolver (created on the first call).
StationResolverObject(const StationSpec *statspec, BaseStation *st, TileIndex tile, CallbackID callback=CBID_NO_CALLBACK, uint32_t callback_param1=0, uint32_t callback_param2=0)
Resolver for stations.
const SpriteGroup * ResolveReal(const RealSpriteGroup &group) const override
Get the real sprites of the grf.
GrfSpecFeature GetFeature() const override
Get the feature number being resolved for.
struct BaseStation * st
Instance of the station.
uint32_t GetRandomTriggers() const override
Get the triggers.
uint32_t GetVariable(uint8_t variable, uint32_t parameter, bool &available) const override
Get a variable value.
uint32_t GetRandomBits() const override
Get a few random bits.
const struct StationSpec * statspec
Station (type) specification.
Axis axis
Station axis, used only for the slope check callback.
TileIndex tile
Tile of the station.
Station specification.
CargoGRFFileProps grf_prop
Link to NewGRF.
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
StationCallbackMasks callback_mask
Bitmask of station callbacks that have to be called.
StationSpecFlags flags
Bitmask of flags, bit 0: use different sprite set; bit 1: divide cargo about by station size.
Station data structure.
RoadStop * bus_stops
All the road stops.
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
bool TileBelongsToRailStation(TileIndex tile) const override
Check whether a specific tile belongs to this station.
Airport airport
Tile area the airport covers.
RoadStop * truck_stops
All the truck stops.
Scope resolver for a town.
Definition newgrf_town.h:22
Town data structure.
Definition town.h:64
uint32_t GetNewGRFVariable(const struct ResolverObject &object, uint8_t variable, uint8_t parameter, bool &available) const override
Helper function to get a NewGRF variable that isn't implemented by the base class.
Generic 'commands' that can be performed on all tiles.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
uint8_t GetAnimationFrame(Tile t)
Get the current animation frame.
Definition tile_map.h:250
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
@ TunnelBridge
Tunnel entry/exit and bridge heads.
Definition tile_type.h:58
@ Station
A tile of a station or airport.
Definition tile_type.h:54
OrthogonalTileArea TileArea
Shorthand for the much more common orthogonal tile area.
Definition of the game-calendar-timer.
Base of the town class.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
TrackBits DiagdirReachesTracks(DiagDirection diagdir)
Returns all tracks that can be reached when entering a tile from a given (diagonal) direction.
Definition track_func.h:468
TrackBits TrackdirBitsToTrackBits(TrackdirBits bits)
Discards all directional information from a TrackdirBits value.
Definition track_func.h:281
EnumBitSet< Track, uint8_t > TrackBits
Bitset of Track elements.
Definition track_type.h:43
@ Rail
Transport by train.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
Base of waypoints.