# newgrf_station.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_station.cpp 19300 2010-03-02 00:38:01Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "variables.h"
    00014 #include "debug.h"
    00015 #include "station_base.h"
    00016 #include "waypoint_base.h"
    00017 #include "roadstop_base.h"
    00018 #include "newgrf_cargo.h"
    00019 #include "newgrf_commons.h"
    00020 #include "newgrf_station.h"
    00021 #include "newgrf_spritegroup.h"
    00022 #include "newgrf_sound.h"
    00023 #include "newgrf_railtype.h"
    00024 #include "town.h"
    00025 #include "newgrf_town.h"
    00026 #include "date_func.h"
    00027 #include "company_func.h"
    00028 #include "animated_tile_func.h"
    00029 #include "functions.h"
    00030 #include "tunnelbridge_map.h"
    00031 #include "newgrf.h"
    00032 #include "core/random_func.hpp"
    00033
    00034 #include "table/strings.h"
    00035
    00036 static StationClass _station_classes[STAT_CLASS_MAX];
    00037
    00038 enum {
    00039   MAX_SPECLIST = 255,
    00040 };
    00041
    00042 enum TriggerArea {
    00043   TA_TILE,
    00044   TA_PLATFORM,
    00045   TA_WHOLE,
    00046 };
    00047
    00048 struct ETileArea : TileArea {
    00049   ETileArea(const BaseStation *st, TileIndex tile, TriggerArea ta)
    00050   {
    00051     switch (ta) {
    00052       default: NOT_REACHED();
    00053
    00054       case TA_TILE:
    00055         this->tile = tile;
    00056         this->w    = 1;
    00057         this->h    = 1;
    00058         break;
    00059
    00060       case TA_PLATFORM: {
    00061         TileIndex start, end;
    00062         Axis axis = GetRailStationAxis(tile);
    00063         TileIndexDiff delta = TileOffsByDiagDir(AxisToDiagDir(axis));
    00064
    00065         for (end = tile; IsRailStationTile(end + delta) && IsCompatibleTrainStationTile(tile, end + delta); end += delta) { /* Nothing */ }
    00066         for (start = tile; IsRailStationTile(start - delta) && IsCompatibleTrainStationTile(tile, start - delta); start -= delta) { /* Nothing */ }
    00067
    00068         this->tile = start;
    00069         this->w = TileX(end) - TileX(start) + 1;
    00070         this->h = TileY(end) - TileY(start) + 1;
    00071         break;
    00072       }
    00073
    00074       case TA_WHOLE:
    00075         st->GetTileArea(this, Station::IsExpected(st) ? STATION_RAIL : STATION_WAYPOINT);
    00076         break;
    00077     }
    00078   }
    00079 };
    00080
    00081
    00087 void ResetStationClasses()
    00088 {
    00089   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
    00090     _station_classes[i].id = 0;
    00091     _station_classes[i].name = STR_EMPTY;
    00092     _station_classes[i].stations = 0;
    00093
    00094     free(_station_classes[i].spec);
    00095     _station_classes[i].spec = NULL;
    00096   }
    00097
    00098   /* Set up initial data */
    00099   _station_classes[0].id = 'DFLT';
    00100   _station_classes[0].name = STR_STATION_CLASS_DFLT;
    00101   _station_classes[0].stations = 1;
    00102   _station_classes[0].spec = MallocT<StationSpec*>(1);
    00103   _station_classes[0].spec[0] = NULL;
    00104
    00105   _station_classes[1].id = 'WAYP';
    00106   _station_classes[1].name = STR_STATION_CLASS_WAYP;
    00107   _station_classes[1].stations = 1;
    00108   _station_classes[1].spec = MallocT<StationSpec*>(1);
    00109   _station_classes[1].spec[0] = NULL;
    00110 }
    00111
    00117 StationClassID AllocateStationClass(uint32 cls)
    00118 {
    00119   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
    00120     if (_station_classes[i].id == cls) {
    00121       /* ClassID is already allocated, so reuse it. */
    00122       return i;
    00123     } else if (_station_classes[i].id == 0) {
    00124       /* This class is empty, so allocate it to the ClassID. */
    00125       _station_classes[i].id = cls;
    00126       return i;
    00127     }
    00128   }
    00129
    00130   grfmsg(2, "StationClassAllocate: already allocated %d classes, using default", STAT_CLASS_MAX);
    00131   return STAT_CLASS_DFLT;
    00132 }
    00133
    00135 void SetStationClassName(StationClassID sclass, StringID name)
    00136 {
    00137   assert(sclass < STAT_CLASS_MAX);
    00138   _station_classes[sclass].name = name;
    00139 }
    00140
    00142 StringID GetStationClassName(StationClassID sclass)
    00143 {
    00144   assert(sclass < STAT_CLASS_MAX);
    00145   return _station_classes[sclass].name;
    00146 }
    00147
    00152 uint GetNumStationClasses()
    00153 {
    00154   uint i;
    00155   for (i = 0; i < STAT_CLASS_MAX && _station_classes[i].id != 0; i++) {}
    00156   return i;
    00157 }
    00158
    00164 uint GetNumCustomStations(StationClassID sclass)
    00165 {
    00166   assert(sclass < STAT_CLASS_MAX);
    00167   return _station_classes[sclass].stations;
    00168 }
    00169
    00174 void SetCustomStationSpec(StationSpec *statspec)
    00175 {
    00176   StationClass *station_class;
    00177   int i;
    00178
    00179   /* If the station has already been allocated, don't reallocate it. */
    00180   if (statspec->allocated) return;
    00181
    00182   assert(statspec->sclass < STAT_CLASS_MAX);
    00183   station_class = &_station_classes[statspec->sclass];
    00184
    00185   i = station_class->stations++;
    00186   station_class->spec = ReallocT(station_class->spec, station_class->stations);
    00187
    00188   station_class->spec[i] = statspec;
    00189   statspec->allocated = true;
    00190 }
    00191
    00198 const StationSpec *GetCustomStationSpec(StationClassID sclass, uint station)
    00199 {
    00200   assert(sclass < STAT_CLASS_MAX);
    00201   if (station < _station_classes[sclass].stations)
    00202     return _station_classes[sclass].spec[station];
    00203
    00204   /* If the custom station isn't defined any more, then the GRF file
    00205    * probably was not loaded. */
    00206   return NULL;
    00207 }
    00208
    00216 const StationSpec *GetCustomStationSpecByGrf(uint32 grfid, byte localidx, int *index)
    00217 {
    00218   uint j;
    00219
    00220   for (StationClassID i = STAT_CLASS_BEGIN; i < STAT_CLASS_MAX; i++) {
    00221     for (j = 0; j < _station_classes[i].stations; j++) {
    00222       const StationSpec *statspec = _station_classes[i].spec[j];
    00223       if (statspec == NULL) continue;
    00224       if (statspec->grffile->grfid == grfid && statspec->localidx == localidx) {
    00225         if (index != NULL) *index = j;
    00226         return statspec;
    00227       }
    00228     }
    00229   }
    00230
    00231   return NULL;
    00232 }
    00233
    00234
    00235 /* Evaluate a tile's position within a station, and return the result a bitstuffed format.
    00236  * if not centred: .TNLcCpP, if centred: .TNL..CP
    00237  * T = Tile layout number (GetStationGfx), N = Number of platforms, L = Length of platforms
    00238  * C = Current platform number from start, c = from end
    00239  * P = Position along platform from start, p = from end
    00240  * if centred, C/P start from the centre and c/p are not available.
    00241  */
    00242 uint32 GetPlatformInfo(Axis axis, byte tile, int platforms, int length, int x, int y, bool centred)
    00243 {
    00244   uint32 retval = 0;
    00245
    00246   if (axis == AXIS_X) {
    00247     Swap(platforms, length);
    00248     Swap(x, y);
    00249   }
    00250
    00251   /* Limit our sizes to 4 bits */
    00252   platforms = min(15, platforms);
    00253   length    = min(15, length);
    00254   x = min(15, x);
    00255   y = min(15, y);
    00256   if (centred) {
    00257     x -= platforms / 2;
    00258     y -= length / 2;
    00259     SB(retval,  0, 4, y & 0xF);
    00260     SB(retval,  4, 4, x & 0xF);
    00261   } else {
    00262     SB(retval,  0, 4, y);
    00263     SB(retval,  4, 4, length - y - 1);
    00264     SB(retval,  8, 4, x);
    00265     SB(retval, 12, 4, platforms - x - 1);
    00266   }
    00267   SB(retval, 16, 4, length);
    00268   SB(retval, 20, 4, platforms);
    00269   SB(retval, 24, 4, tile);
    00270
    00271   return retval;
    00272 }
    00273
    00274
    00275 /* Find the end of a railway station, from the tile, in the direction of delta.
    00276  * If check_type is set, we stop if the custom station type changes.
    00277  * If check_axis is set, we stop if the station direction changes.
    00278  */
    00279 static TileIndex FindRailStationEnd(TileIndex tile, TileIndexDiff delta, bool check_type, bool check_axis)
    00280 {
    00281   byte orig_type = 0;
    00282   Axis orig_axis = AXIS_X;
    00283   StationID sid = GetStationIndex(tile);
    00284
    00285   if (check_type) orig_type = GetCustomStationSpecIndex(tile);
    00286   if (check_axis) orig_axis = GetRailStationAxis(tile);
    00287
    00288   while (true) {
    00289     TileIndex new_tile = TILE_ADD(tile, delta);
    00290
    00291     if (!IsTileType(new_tile, MP_STATION) || GetStationIndex(new_tile) != sid) break;
    00292     if (!HasStationRail(new_tile)) break;
    00293     if (check_type && GetCustomStationSpecIndex(new_tile) != orig_type) break;
    00294     if (check_axis && GetRailStationAxis(new_tile) != orig_axis) break;
    00295
    00296     tile = new_tile;
    00297   }
    00298   return tile;
    00299 }
    00300
    00301
    00302 static uint32 GetPlatformInfoHelper(TileIndex tile, bool check_type, bool check_axis, bool centred)
    00303 {
    00304   int tx = TileX(tile);
    00305   int ty = TileY(tile);
    00306   int sx = TileX(FindRailStationEnd(tile, TileDiffXY(-1,  0), check_type, check_axis));
    00307   int sy = TileY(FindRailStationEnd(tile, TileDiffXY( 0, -1), check_type, check_axis));
    00308   int ex = TileX(FindRailStationEnd(tile, TileDiffXY( 1,  0), check_type, check_axis)) + 1;
    00309   int ey = TileY(FindRailStationEnd(tile, TileDiffXY( 0,  1), check_type, check_axis)) + 1;
    00310
    00311   tx -= sx; ex -= sx;
    00312   ty -= sy; ey -= sy;
    00313
    00314   return GetPlatformInfo(GetRailStationAxis(tile), GetStationGfx(tile), ex, ey, tx, ty, centred);
    00315 }
    00316
    00317
    00318 static uint32 GetRailContinuationInfo(TileIndex tile)
    00319 {
    00320   /* Tile offsets and exit dirs for X axis */
    00321   static const Direction x_dir[8] = { DIR_SW, DIR_NE, DIR_SE, DIR_NW, DIR_S, DIR_E, DIR_W, DIR_N };
    00322   static const DiagDirection x_exits[8] = { DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SW, DIAGDIR_NE };
    00323
    00324   /* Tile offsets and exit dirs for Y axis */
    00325   static const Direction y_dir[8] = { DIR_SE, DIR_NW, DIR_SW, DIR_NE, DIR_S, DIR_W, DIR_E, DIR_N };
    00326   static const DiagDirection y_exits[8] = { DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SW, DIAGDIR_NE, DIAGDIR_SE, DIAGDIR_NW, DIAGDIR_SE, DIAGDIR_NW };
    00327
    00328   Axis axis = GetRailStationAxis(tile);
    00329
    00330   /* Choose appropriate lookup table to use */
    00331   const Direction *dir = axis == AXIS_X ? x_dir : y_dir;
    00332   const DiagDirection *diagdir = axis == AXIS_X ? x_exits : y_exits;
    00333
    00334   uint32 res = 0;
    00335   uint i;
    00336
    00337   for (i = 0; i < lengthof(x_dir); i++, dir++, diagdir++) {
    00338     TileIndex neighbour_tile = tile + TileOffsByDir(*dir);
    00339     TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile, TRANSPORT_RAIL, 0));
    00340     if (trackbits != TRACK_BIT_NONE) {
    00341       /* If there is any track on the tile, set the bit in the second byte */
    00342       SetBit(res, i + 8);
    00343
    00344       /* With tunnels and bridges the tile has tracks, but they are not necessarily connected
    00345        * with the next tile because the ramp is not going in the right direction. */
    00346       if (IsTileType(neighbour_tile, MP_TUNNELBRIDGE) && GetTunnelBridgeDirection(neighbour_tile) != *diagdir) {
    00347         continue;
    00348       }
    00349
    00350       /* If any track reaches our exit direction, set the bit in the lower byte */
    00351       if (trackbits & DiagdirReachesTracks(*diagdir)) SetBit(res, i);
    00352     }
    00353   }
    00354
    00355   return res;
    00356 }
    00357
    00358
    00359 /* Station Resolver Functions */
    00360 static uint32 StationGetRandomBits(const ResolverObject *object)
    00361 {
    00362   const BaseStation *st = object->u.station.st;
    00363   const TileIndex tile = object->u.station.tile;
    00364   return (st == NULL ? 0 : st->random_bits) | (tile == INVALID_TILE ? 0 : GetStationTileRandomBits(tile) << 16);
    00365 }
    00366
    00367
    00368 static uint32 StationGetTriggers(const ResolverObject *object)
    00369 {
    00370   const BaseStation *st = object->u.station.st;
    00371   return st == NULL ? 0 : st->waiting_triggers;
    00372 }
    00373
    00374
    00375 static void StationSetTriggers(const ResolverObject *object, int triggers)
    00376 {
    00377   BaseStation *st = const_cast<BaseStation *>(object->u.station.st);
    00378   assert(st != NULL);
    00379   st->waiting_triggers = triggers;
    00380 }
    00381
    00387 static struct {
    00388   uint32 v40;
    00389   uint32 v41;
    00390   uint32 v45;
    00391   uint32 v46;
    00392   uint32 v47;
    00393   uint32 v49;
    00394   uint8 valid;
    00395 } _svc;
    00396
    00397 static uint32 StationGetVariable(const ResolverObject *object, byte variable, byte parameter, bool *available)
    00398 {
    00399   const BaseStation *st = object->u.station.st;
    00400   TileIndex tile = object->u.station.tile;
    00401
    00402   if (object->scope == VSG_SCOPE_PARENT) {
    00403     /* Pass the request on to the town of the station */
    00404     const Town *t;
    00405
    00406     if (st != NULL) {
    00407       t = st->town;
    00408     } else if (tile != INVALID_TILE) {
    00409       t = ClosestTownFromTile(tile, UINT_MAX);
    00410     } else {
    00411       *available = false;
    00412       return UINT_MAX;
    00413     }
    00414
    00415     return TownGetVariable(variable, parameter, available, t);
    00416   }
    00417
    00418   if (st == NULL) {
    00419     /* Station does not exist, so we're in a purchase list */
    00420     switch (variable) {
    00421       case 0x40:
    00422       case 0x41:
    00423       case 0x46:
    00424       case 0x47:
    00425       case 0x49: return 0x2110000;        // Platforms, tracks & position
    00426       case 0x42: return 0;                // Rail type (XXX Get current type from GUI?)
    00427       case 0x43: return _current_company; // Station owner
    00428       case 0x44: return 2;                // PBS status
    00429       case 0xFA: return Clamp(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Build date, clamped to a 16 bit value
    00430     }
    00431
    00432     *available = false;
    00433     return UINT_MAX;
    00434   }
    00435
    00436   switch (variable) {
    00437     /* Calculated station variables */
    00438     case 0x40:
    00439       if (!HasBit(_svc.valid, 0)) { _svc.v40 = GetPlatformInfoHelper(tile, false, false, false); SetBit(_svc.valid, 0); }
    00440       return _svc.v40;
    00441
    00442     case 0x41:
    00443       if (!HasBit(_svc.valid, 1)) { _svc.v41 = GetPlatformInfoHelper(tile, true,  false, false); SetBit(_svc.valid, 1); }
    00444       return _svc.v41;
    00445
    00446     case 0x42: return GetTerrainType(tile) | (GetReverseRailTypeTranslation(GetRailType(tile), object->u.station.statspec->grffile) << 8);
    00447     case 0x43: return st->owner; // Station owner
    00448     case 0x44: return HasStationReservation(tile) ? 7 : 4; // PBS status
    00449     case 0x45:
    00450       if (!HasBit(_svc.valid, 2)) { _svc.v45 = GetRailContinuationInfo(tile); SetBit(_svc.valid, 2); }
    00451       return _svc.v45;
    00452
    00453     case 0x46:
    00454       if (!HasBit(_svc.valid, 3)) { _svc.v46 = GetPlatformInfoHelper(tile, false, false, true); SetBit(_svc.valid, 3); }
    00455       return _svc.v46;
    00456
    00457     case 0x47:
    00458       if (!HasBit(_svc.valid, 4)) { _svc.v47 = GetPlatformInfoHelper(tile, true,  false, true); SetBit(_svc.valid, 4); }
    00459       return _svc.v47;
    00460
    00461     case 0x49:
    00462       if (!HasBit(_svc.valid, 5)) { _svc.v49 = GetPlatformInfoHelper(tile, false, true, false); SetBit(_svc.valid, 5); }
    00463       return _svc.v49;
    00464
    00465     case 0x4A: // Animation frame of tile
    00466       return GetStationAnimationFrame(tile);
    00467
    00468     /* Variables which use the parameter */
    00469     /* Variables 0x60 to 0x65 are handled separately below */
    00470     case 0x66: // Animation frame of nearby tile
    00471       if (parameter != 0) tile = GetNearbyTile(parameter, tile);
    00472       return st->TileBelongsToRailStation(tile) ? GetStationAnimationFrame(tile) : UINT_MAX;
    00473
    00474     case 0x67: { // Land info of nearby tile
    00475       Axis axis = GetRailStationAxis(tile);
    00476
    00477       if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
    00478
    00479       Slope tileh = GetTileSlope(tile, NULL);
    00480       bool swap = (axis == AXIS_Y && HasBit(tileh, CORNER_W) != HasBit(tileh, CORNER_E));
    00481
    00482       return GetNearbyTileInformation(tile) ^ (swap ? SLOPE_EW : 0);
    00483     }
    00484
    00485     case 0x68: { // Station info of nearby tiles
    00486       TileIndex nearby_tile = GetNearbyTile(parameter, tile);
    00487
    00488       if (!HasStationTileRail(nearby_tile)) return 0xFFFFFFFF;
    00489
    00490       uint32 grfid = st->speclist[GetCustomStationSpecIndex(tile)].grfid;
    00491       bool perpendicular = GetRailStationAxis(tile) != GetRailStationAxis(nearby_tile);
    00492       bool same_station = st->TileBelongsToRailStation(nearby_tile);
    00493       uint32 res = GB(GetStationGfx(nearby_tile), 1, 2) << 12 | !!perpendicular << 11 | !!same_station << 10;
    00494
    00495       if (IsCustomStationSpecIndex(nearby_tile)) {
    00496         const StationSpecList ssl = BaseStation::GetByTile(nearby_tile)->speclist[GetCustomStationSpecIndex(nearby_tile)];
    00497         res |= 1 << (ssl.grfid != grfid ? 9 : 8) | ssl.localidx;
    00498       }
    00499       return res;
    00500     }
    00501
    00502     /* General station variables */
    00503     case 0x82: return 50;
    00504     case 0x84: return st->string_id;
    00505     case 0x86: return 0;
    00506     case 0xF0: return st->facilities;
    00507     case 0xFA: return Clamp(st->build_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535);
    00508   }
    00509
    00510   return st->GetNewGRFVariable(object, variable, parameter, available);
    00511 }
    00512
    00513 byte MapAirportTypeToTTDType(byte ottd_type);
    00514
    00515 uint32 Station::GetNewGRFVariable(const ResolverObject *object, byte variable, byte parameter, bool *available) const
    00516 {
    00517   switch (variable) {
    00518     case 0x48: { // Accepted cargo types
    00519       CargoID cargo_type;
    00520       uint32 value = 0;
    00521
    00522       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
    00523         if (HasBit(this->goods[cargo_type].acceptance_pickup, GoodsEntry::PICKUP)) SetBit(value, cargo_type);
    00524       }
    00525       return value;
    00526     }
    00527
    00528     case 0x8A: return this->had_vehicle_of_type;
    00529     case 0xF1: return MapAirportTypeToTTDType(this->airport_type);
    00530     case 0xF2: return (this->truck_stops != NULL) ? this->truck_stops->status : 0;
    00531     case 0xF3: return (this->bus_stops != NULL)   ? this->bus_stops->status   : 0;
    00532     case 0xF6: return this->airport_flags;
    00533     case 0xF7: return GB(this->airport_flags, 8, 8);
    00534   }
    00535
    00536   /* Handle cargo variables with parameter, 0x60 to 0x65 */
    00537   if (variable >= 0x60 && variable <= 0x65) {
    00538     CargoID c = GetCargoTranslation(parameter, object->u.station.statspec->grffile);
    00539
    00540     if (c == CT_INVALID) return 0;
    00541     const GoodsEntry *ge = &this->goods[c];
    00542
    00543     switch (variable) {
    00544       case 0x60: return min(ge->cargo.Count(), 4095);
    00545       case 0x61: return ge->days_since_pickup;
    00546       case 0x62: return ge->rating;
    00547       case 0x63: return ge->cargo.DaysInTransit();
    00548       case 0x64: return ge->last_speed | (ge->last_age << 8);
    00549       case 0x65: return GB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 3;
    00550     }
    00551   }
    00552
    00553   /* Handle cargo variables (deprecated) */
    00554   if (variable >= 0x8C && variable <= 0xEC) {
    00555     const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
    00556     switch (GB(variable - 0x8C, 0, 3)) {
    00557       case 0: return g->cargo.Count();
    00558       case 1: return GB(min(g->cargo.Count(), 4095), 0, 4) | (GB(g->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 7);
    00559       case 2: return g->days_since_pickup;
    00560       case 3: return g->rating;
    00561       case 4: return g->cargo.Source();
    00562       case 5: return g->cargo.DaysInTransit();
    00563       case 6: return g->last_speed;
    00564       case 7: return g->last_age;
    00565     }
    00566   }
    00567
    00568   DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
    00569
    00570   *available = false;
    00571   return UINT_MAX;
    00572 }
    00573
    00574 uint32 Waypoint::GetNewGRFVariable(const ResolverObject *object, byte variable, byte parameter, bool *available) const
    00575 {
    00576   switch (variable) {
    00577     case 0x48: return 0; // Accepted cargo types
    00578     case 0x8A: return HVOT_WAYPOINT;
    00579     case 0xF1: return 0; // airport type
    00580     case 0xF2: return 0; // truck stop status
    00581     case 0xF3: return 0; // bus stop status
    00582     case 0xF6: return 0; // airport flags
    00583     case 0xF7: return 0; // airport flags cont.
    00584   }
    00585
    00586   /* Handle cargo variables with parameter, 0x60 to 0x65 */
    00587   if (variable >= 0x60 && variable <= 0x65) {
    00588     return 0;
    00589   }
    00590
    00591   /* Handle cargo variables (deprecated) */
    00592   if (variable >= 0x8C && variable <= 0xEC) {
    00593     switch (GB(variable - 0x8C, 0, 3)) {
    00594       case 3: return INITIAL_STATION_RATING;
    00595       case 4: return INVALID_STATION;
    00596       default: return 0;
    00597     }
    00598   }
    00599
    00600   DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
    00601
    00602   *available = false;
    00603   return UINT_MAX;
    00604 }
    00605
    00606 static const SpriteGroup *StationResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
    00607 {
    00608   const BaseStation *bst = object->u.station.st;
    00609   const StationSpec *statspec = object->u.station.statspec;
    00610   uint set;
    00611
    00612   uint cargo = 0;
    00613   CargoID cargo_type = object->u.station.cargo_type;
    00614
    00615   if (bst == NULL || statspec->sclass == STAT_CLASS_WAYP) {
    00616     return group->loading[0];
    00617   }
    00618
    00619   const Station *st = Station::From(bst);
    00620
    00621   switch (cargo_type) {
    00622     case CT_INVALID:
    00623     case CT_DEFAULT_NA:
    00624     case CT_PURCHASE:
    00625       cargo = 0;
    00626       break;
    00627
    00628     case CT_DEFAULT:
    00629       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
    00630         cargo += st->goods[cargo_type].cargo.Count();
    00631       }
    00632       break;
    00633
    00634     default:
    00635       cargo = st->goods[cargo_type].cargo.Count();
    00636       break;
    00637   }
    00638
    00639   if (HasBit(statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
    00640   cargo = min(0xfff, cargo);
    00641
    00642   if (cargo > statspec->cargo_threshold) {
    00643     if (group->num_loading > 0) {
    00644       set = ((cargo - statspec->cargo_threshold) * group->num_loading) / (4096 - statspec->cargo_threshold);
    00645       return group->loading[set];
    00646     }
    00647   } else {
    00648     if (group->num_loaded > 0) {
    00649       set = (cargo * group->num_loaded) / (statspec->cargo_threshold + 1);
    00650       return group->loaded[set];
    00651     }
    00652   }
    00653
    00654   return group->loading[0];
    00655 }
    00656
    00657
    00658 static void NewStationResolver(ResolverObject *res, const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00659 {
    00660   res->GetRandomBits = StationGetRandomBits;
    00661   res->GetTriggers   = StationGetTriggers;
    00662   res->SetTriggers   = StationSetTriggers;
    00663   res->GetVariable   = StationGetVariable;
    00664   res->ResolveReal   = StationResolveReal;
    00665
    00666   res->u.station.st       = st;
    00667   res->u.station.statspec = statspec;
    00668   res->u.station.tile     = tile;
    00669
    00670   res->callback        = CBID_NO_CALLBACK;
    00671   res->callback_param1 = 0;
    00672   res->callback_param2 = 0;
    00673   res->last_value      = 0;
    00674   res->trigger         = 0;
    00675   res->reseed          = 0;
    00676   res->count           = 0;
    00677   res->grffile         = (statspec != NULL ? statspec->grffile : NULL);
    00678 }
    00679
    00680 static const SpriteGroup *ResolveStation(ResolverObject *object)
    00681 {
    00682   const SpriteGroup *group;
    00683   CargoID ctype = CT_DEFAULT_NA;
    00684
    00685   if (object->u.station.st == NULL) {
    00686     /* No station, so we are in a purchase list */
    00687     ctype = CT_PURCHASE;
    00688   } else if (Station::IsExpected(object->u.station.st)) {
    00689     const Station *st = Station::From(object->u.station.st);
    00690     /* Pick the first cargo that we have waiting */
    00691     const CargoSpec *cs;
    00692     FOR_ALL_CARGOSPECS(cs) {
    00693       if (object->u.station.statspec->spritegroup[cs->Index()] != NULL &&
    00694           !st->goods[cs->Index()].cargo.Empty()) {
    00695         ctype = cs->Index();
    00696         break;
    00697       }
    00698     }
    00699   }
    00700
    00701   group = object->u.station.statspec->spritegroup[ctype];
    00702   if (group == NULL) {
    00703     ctype = CT_DEFAULT;
    00704     group = object->u.station.statspec->spritegroup[ctype];
    00705   }
    00706
    00707   if (group == NULL) return NULL;
    00708
    00709   /* Remember the cargo type we've picked */
    00710   object->u.station.cargo_type = ctype;
    00711
    00712   /* Invalidate all cached vars */
    00713   _svc.valid = 0;
    00714
    00715   return SpriteGroup::Resolve(group, object);
    00716 }
    00717
    00718 SpriteID GetCustomStationRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00719 {
    00720   const SpriteGroup *group;
    00721   ResolverObject object;
    00722
    00723   NewStationResolver(&object, statspec, st, tile);
    00724
    00725   group = ResolveStation(&object);
    00726   if (group == NULL || group->type != SGT_RESULT) return 0;
    00727   return group->GetResult() - 0x42D;
    00728 }
    00729
    00730
    00731 SpriteID GetCustomStationGroundRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00732 {
    00733   const SpriteGroup *group;
    00734   ResolverObject object;
    00735
    00736   NewStationResolver(&object, statspec, st, tile);
    00737   if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
    00738     object.callback_param1 = 1; // Indicate we are resolving the ground sprite
    00739   }
    00740
    00741   group = ResolveStation(&object);
    00742   if (group == NULL || group->type != SGT_RESULT) return 0;
    00743   return group->GetResult() - 0x42D;
    00744 }
    00745
    00746
    00747 SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00748 {
    00749   const SpriteGroup *group;
    00750   ResolverObject object;
    00751
    00752   NewStationResolver(&object, statspec, st, tile);
    00753   object.callback_param1 = 2; // Indicate we are resolving the foundation sprites
    00754
    00755   group = ResolveStation(&object);
    00756   if (group == NULL || group->type != SGT_RESULT) return 0;
    00757   return group->GetResult() + GetRegister(0x100);
    00758 }
    00759
    00760
    00761 uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00762 {
    00763   const SpriteGroup *group;
    00764   ResolverObject object;
    00765
    00766   NewStationResolver(&object, statspec, st, tile);
    00767
    00768   object.callback        = callback;
    00769   object.callback_param1 = param1;
    00770   object.callback_param2 = param2;
    00771
    00772   group = ResolveStation(&object);
    00773   if (group == NULL) return CALLBACK_FAILED;
    00774   return group->GetCallbackResult();
    00775 }
    00776
    00777
    00785 int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
    00786 {
    00787   uint i;
    00788
    00789   if (statspec == NULL || st == NULL) return 0;
    00790
    00791   for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
    00792     if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
    00793   }
    00794
    00795   if (i == MAX_SPECLIST) {
    00796     /* As final effort when the spec list is already full...
    00797      * try to find the same spec and return that one. This might
    00798      * result in slighty "wrong" (as per specs) looking stations,
    00799      * but it's fairly unlikely that one reaches the limit anyways.
    00800      */
    00801     for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
    00802       if (st->speclist[i].spec == statspec) return i;
    00803     }
    00804
    00805     return -1;
    00806   }
    00807
    00808   if (exec) {
    00809     if (i >= st->num_specs) {
    00810       st->num_specs = i + 1;
    00811       st->speclist = ReallocT(st->speclist, st->num_specs);
    00812
    00813       if (st->num_specs == 2) {
    00814         /* Initial allocation */
    00815         st->speclist[0].spec     = NULL;
    00816         st->speclist[0].grfid    = 0;
    00817         st->speclist[0].localidx = 0;
    00818       }
    00819     }
    00820
    00821     st->speclist[i].spec     = statspec;
    00822     st->speclist[i].grfid    = statspec->grffile->grfid;
    00823     st->speclist[i].localidx = statspec->localidx;
    00824   }
    00825
    00826   return i;
    00827 }
    00828
    00829
    00835 void DeallocateSpecFromStation(BaseStation *st, byte specindex)
    00836 {
    00837   /* specindex of 0 (default) is never freeable */
    00838   if (specindex == 0) return;
    00839
    00840   ETileArea area = ETileArea(st, INVALID_TILE, TA_WHOLE);
    00841   /* Check all tiles over the station to check if the specindex is still in use */
    00842   TILE_AREA_LOOP(tile, area) {
    00843     if (st->TileBelongsToRailStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
    00844       return;
    00845     }
    00846   }
    00847
    00848   /* This specindex is no longer in use, so deallocate it */
    00849   st->speclist[specindex].spec     = NULL;
    00850   st->speclist[specindex].grfid    = 0;
    00851   st->speclist[specindex].localidx = 0;
    00852
    00853   /* If this was the highest spec index, reallocate */
    00854   if (specindex == st->num_specs - 1) {
    00855     for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
    00856
    00857     if (st->num_specs > 1) {
    00858       st->speclist = ReallocT(st->speclist, st->num_specs);
    00859     } else {
    00860       free(st->speclist);
    00861       st->num_specs = 0;
    00862       st->speclist  = NULL;
    00863       st->cached_anim_triggers = 0;
    00864       return;
    00865     }
    00866   }
    00867
    00868   StationUpdateAnimTriggers(st);
    00869 }
    00870
    00880 bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
    00881 {
    00882   const StationSpec *statspec;
    00883   const DrawTileSprites *sprites;
    00884   const RailtypeInfo *rti = GetRailTypeInfo(railtype);
    00885   PaletteID palette = COMPANY_SPRITE_COLOUR(_local_company);
    00886   uint tile = 2;
    00887
    00888   statspec = GetCustomStationSpec(sclass, station);
    00889   if (statspec == NULL) return false;
    00890
    00891   uint relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE);
    00892
    00893   if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
    00894     uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
    00895     if (callback != CALLBACK_FAILED) tile = callback;
    00896   }
    00897
    00898   if (statspec->renderdata == NULL) {
    00899     sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
    00900   } else {
    00901     sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
    00902   }
    00903
    00904   SpriteID image = sprites->ground.sprite;
    00905   PaletteID pal = sprites->ground.pal;
    00906   if (HasBit(image, SPRITE_MODIFIER_CUSTOM_SPRITE)) {
    00907     image += GetCustomStationGroundRelocation(statspec, NULL, INVALID_TILE);
    00908     image += rti->custom_ground_offset;
    00909   } else {
    00910     image += rti->total_offset;
    00911   }
    00912
    00913   DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
    00914
    00915   DrawRailTileSeqInGUI(x, y, sprites, rti->total_offset, relocation, palette);
    00916
    00917   return true;
    00918 }
    00919
    00920
    00921 const StationSpec *GetStationSpec(TileIndex t)
    00922 {
    00923   if (!IsCustomStationSpecIndex(t)) return NULL;
    00924
    00925   const BaseStation *st = BaseStation::GetByTile(t);
    00926   uint specindex = GetCustomStationSpecIndex(t);
    00927   return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
    00928 }
    00929
    00930
    00931 /* Check if a rail station tile is traversable.
    00932  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
    00933 bool IsStationTileBlocked(TileIndex tile)
    00934 {
    00935   const StationSpec *statspec = GetStationSpec(tile);
    00936
    00937   return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
    00938 }
    00939
    00940 /* Check if a rail station tile is electrifiable.
    00941  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
    00942 bool IsStationTileElectrifiable(TileIndex tile)
    00943 {
    00944   const StationSpec *statspec = GetStationSpec(tile);
    00945
    00946   return
    00947     statspec == NULL ||
    00948     HasBit(statspec->pylons, GetStationGfx(tile)) ||
    00949     !HasBit(statspec->wires, GetStationGfx(tile));
    00950 }
    00951
    00952 void AnimateStationTile(TileIndex tile)
    00953 {
    00954   const StationSpec *ss = GetStationSpec(tile);
    00955   if (ss == NULL) return;
    00956
    00957   const BaseStation *st = BaseStation::GetByTile(tile);
    00958
    00959   uint8 animation_speed = ss->anim_speed;
    00960
    00961   if (HasBit(ss->callback_mask, CBM_STATION_ANIMATION_SPEED)) {
    00962     uint16 callback = GetStationCallback(CBID_STATION_ANIMATION_SPEED, 0, 0, ss, st, tile);
    00963     if (callback != CALLBACK_FAILED) animation_speed = Clamp(callback & 0xFF, 0, 16);
    00964   }
    00965
    00966   if (_tick_counter % (1 << animation_speed) != 0) return;
    00967
    00968   uint8 frame      = GetStationAnimationFrame(tile);
    00969   uint8 num_frames = ss->anim_frames;
    00970
    00971   bool frame_set_by_callback = false;
    00972
    00973   if (HasBit(ss->callback_mask, CBM_STATION_ANIMATION_NEXT_FRAME)) {
    00974     uint32 param = HasBit(ss->flags, SSF_CB141_RANDOM_BITS) ? Random() : 0;
    00975     uint16 callback = GetStationCallback(CBID_STATION_ANIM_NEXT_FRAME, param, 0, ss, st, tile);
    00976
    00977     if (callback != CALLBACK_FAILED) {
    00978       frame_set_by_callback = true;
    00979
    00980       switch (callback & 0xFF) {
    00981         case 0xFF:
    00982           DeleteAnimatedTile(tile);
    00983           break;
    00984
    00985         case 0xFE:
    00986           frame_set_by_callback = false;
    00987           break;
    00988
    00989         default:
    00990           frame = callback & 0xFF;
    00991           break;
    00992       }
    00993
    00994       /* If the lower 7 bits of the upper byte of the callback
    00995        * result are not empty, it is a sound effect. */
    00996       if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
    00997     }
    00998   }
    00999
    01000   if (!frame_set_by_callback) {
    01001     if (frame < num_frames) {
    01002       frame++;
    01003     } else if (frame == num_frames && HasBit(ss->anim_status, 0)) {
    01004       /* This animation loops, so start again from the beginning */
    01005       frame = 0;
    01006     } else {
    01007       /* This animation doesn't loop, so stay here */
    01008       DeleteAnimatedTile(tile);
    01009     }
    01010   }
    01011
    01012   SetStationAnimationFrame(tile, frame);
    01013   MarkTileDirtyByTile(tile);
    01014 }
    01015
    01016
    01017 static void ChangeStationAnimationFrame(const StationSpec *ss, const BaseStation *st, TileIndex tile, uint16 random_bits, StatAnimTrigger trigger, CargoID cargo_type)
    01018 {
    01019   uint16 callback = GetStationCallback(CBID_STATION_ANIM_START_STOP, (random_bits << 16) | Random(), (uint8)trigger | (cargo_type << 8), ss, st, tile);
    01020   if (callback == CALLBACK_FAILED) return;
    01021
    01022   switch (callback & 0xFF) {
    01023     case 0xFD: /* Do nothing. */         break;
    01024     case 0xFE: AddAnimatedTile(tile);    break;
    01025     case 0xFF: DeleteAnimatedTile(tile); break;
    01026     default:
    01027       SetStationAnimationFrame(tile, callback);
    01028       AddAnimatedTile(tile);
    01029       break;
    01030   }
    01031
    01032   /* If the lower 7 bits of the upper byte of the callback
    01033    * result are not empty, it is a sound effect. */
    01034   if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
    01035 }
    01036
    01037 void StationAnimationTrigger(const BaseStation *st, TileIndex tile, StatAnimTrigger trigger, CargoID cargo_type)
    01038 {
    01039   /* List of coverage areas for each animation trigger */
    01040   static const TriggerArea tas[] = {
    01041     TA_TILE, TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_WHOLE
    01042   };
    01043
    01044   /* Get Station if it wasn't supplied */
    01045   if (st == NULL) st = BaseStation::GetByTile(tile);
    01046
    01047   /* Check the cached animation trigger bitmask to see if we need
    01048    * to bother with any further processing. */
    01049   if (!HasBit(st->cached_anim_triggers, trigger)) return;
    01050
    01051   uint16 random_bits = Random();
    01052   ETileArea area = ETileArea(st, tile, tas[trigger]);
    01053
    01054   /* Check all tiles over the station to check if the specindex is still in use */
    01055   TILE_AREA_LOOP(tile, area) {
    01056     if (st->TileBelongsToRailStation(tile)) {
    01057       const StationSpec *ss = GetStationSpec(tile);
    01058       if (ss != NULL && HasBit(ss->anim_triggers, trigger)) {
    01059         CargoID cargo;
    01060         if (cargo_type == CT_INVALID) {
    01061           cargo = CT_INVALID;
    01062         } else {
    01063           cargo = GetReverseCargoTranslation(cargo_type, ss->grffile);
    01064         }
    01065         ChangeStationAnimationFrame(ss, st, tile, random_bits, trigger, cargo);
    01066       }
    01067     }
    01068   }
    01069 }
    01070
    01075 void StationUpdateAnimTriggers(BaseStation *st)
    01076 {
    01077   st->cached_anim_triggers = 0;
    01078
    01079   /* Combine animation trigger bitmask for all station specs
    01080    * of this station. */
    01081   for (uint i = 0; i < st->num_specs; i++) {
    01082     const StationSpec *ss = st->speclist[i].spec;
    01083     if (ss != NULL) st->cached_anim_triggers |= ss->anim_triggers;
    01084   }
    01085 }