# newgrf_station.cpp

Go to the documentation of this file.

    00001 /* $Id: newgrf_station.cpp 18718 2010-01-04 18:30:10Z 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 "landscape.h"
    00015 #include "debug.h"
    00016 #include "station_base.h"
    00017 #include "waypoint_base.h"
    00018 #include "roadstop_base.h"
    00019 #include "newgrf_cargo.h"
    00020 #include "newgrf_commons.h"
    00021 #include "newgrf_station.h"
    00022 #include "newgrf_spritegroup.h"
    00023 #include "newgrf_sound.h"
    00024 #include "town.h"
    00025 #include "newgrf_town.h"
    00026 #include "gfx_func.h"
    00027 #include "date_func.h"
    00028 #include "company_func.h"
    00029 #include "animated_tile_func.h"
    00030 #include "functions.h"
    00031 #include "tunnelbridge_map.h"
    00032 #include "spritecache.h"
    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) | (GetRailType(tile) << 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, SLOPE_W) != HasBit(tileh, SLOPE_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 uint32 Station::GetNewGRFVariable(const ResolverObject *object, byte variable, byte parameter, bool *available) const
    00514 {
    00515   switch (variable) {
    00516     case 0x48: { // Accepted cargo types
    00517       CargoID cargo_type;
    00518       uint32 value = 0;
    00519
    00520       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
    00521         if (HasBit(this->goods[cargo_type].acceptance_pickup, GoodsEntry::PICKUP)) SetBit(value, cargo_type);
    00522       }
    00523       return value;
    00524     }
    00525
    00526     case 0x8A: return this->had_vehicle_of_type;
    00527     case 0xF1: return this->airport_type;
    00528     case 0xF2: return this->truck_stops->status;
    00529     case 0xF3: return this->bus_stops->status;
    00530     case 0xF6: return this->airport_flags;
    00531     case 0xF7: return GB(this->airport_flags, 8, 8);
    00532   }
    00533
    00534   /* Handle cargo variables with parameter, 0x60 to 0x65 */
    00535   if (variable >= 0x60 && variable <= 0x65) {
    00536     CargoID c = GetCargoTranslation(parameter, object->u.station.statspec->grffile);
    00537
    00538     if (c == CT_INVALID) return 0;
    00539     const GoodsEntry *ge = &this->goods[c];
    00540
    00541     switch (variable) {
    00542       case 0x60: return min(ge->cargo.Count(), 4095);
    00543       case 0x61: return ge->days_since_pickup;
    00544       case 0x62: return ge->rating;
    00545       case 0x63: return ge->cargo.DaysInTransit();
    00546       case 0x64: return ge->last_speed | (ge->last_age << 8);
    00547       case 0x65: return GB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 3;
    00548     }
    00549   }
    00550
    00551   /* Handle cargo variables (deprecated) */
    00552   if (variable >= 0x8C && variable <= 0xEC) {
    00553     const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
    00554     switch (GB(variable - 0x8C, 0, 3)) {
    00555       case 0: return g->cargo.Count();
    00556       case 1: return GB(min(g->cargo.Count(), 4095), 0, 4) | (GB(g->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1) << 7);
    00557       case 2: return g->days_since_pickup;
    00558       case 3: return g->rating;
    00559       case 4: return g->cargo.Source();
    00560       case 5: return g->cargo.DaysInTransit();
    00561       case 6: return g->last_speed;
    00562       case 7: return g->last_age;
    00563     }
    00564   }
    00565
    00566   DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
    00567
    00568   *available = false;
    00569   return UINT_MAX;
    00570 }
    00571
    00572 uint32 Waypoint::GetNewGRFVariable(const ResolverObject *object, byte variable, byte parameter, bool *available) const
    00573 {
    00574   switch (variable) {
    00575     case 0x48: return 0; // Accepted cargo types
    00576     case 0x8A: return HVOT_WAYPOINT;
    00577     case 0xF1: return 0; // airport type
    00578     case 0xF2: return 0; // truck stop status
    00579     case 0xF3: return 0; // bus stop status
    00580     case 0xF6: return 0; // airport flags
    00581     case 0xF7: return 0; // airport flags cont.
    00582   }
    00583
    00584   /* Handle cargo variables with parameter, 0x60 to 0x65 */
    00585   if (variable >= 0x60 && variable <= 0x65) {
    00586     return 0;
    00587   }
    00588
    00589   /* Handle cargo variables (deprecated) */
    00590   if (variable >= 0x8C && variable <= 0xEC) {
    00591     switch (GB(variable - 0x8C, 0, 3)) {
    00592       case 3: return INITIAL_STATION_RATING;
    00593       case 4: return INVALID_STATION;
    00594       default: return 0;
    00595     }
    00596   }
    00597
    00598   DEBUG(grf, 1, "Unhandled station variable 0x%X", variable);
    00599
    00600   *available = false;
    00601   return UINT_MAX;
    00602 }
    00603
    00604 static const SpriteGroup *StationResolveReal(const ResolverObject *object, const RealSpriteGroup *group)
    00605 {
    00606   const BaseStation *bst = object->u.station.st;
    00607   const StationSpec *statspec = object->u.station.statspec;
    00608   uint set;
    00609
    00610   uint cargo = 0;
    00611   CargoID cargo_type = object->u.station.cargo_type;
    00612
    00613   if (bst == NULL || statspec->sclass == STAT_CLASS_WAYP) {
    00614     return group->loading[0];
    00615   }
    00616
    00617   const Station *st = Station::From(bst);
    00618
    00619   switch (cargo_type) {
    00620     case CT_INVALID:
    00621     case CT_DEFAULT_NA:
    00622     case CT_PURCHASE:
    00623       cargo = 0;
    00624       break;
    00625
    00626     case CT_DEFAULT:
    00627       for (cargo_type = 0; cargo_type < NUM_CARGO; cargo_type++) {
    00628         cargo += st->goods[cargo_type].cargo.Count();
    00629       }
    00630       break;
    00631
    00632     default:
    00633       cargo = st->goods[cargo_type].cargo.Count();
    00634       break;
    00635   }
    00636
    00637   if (HasBit(statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
    00638   cargo = min(0xfff, cargo);
    00639
    00640   if (cargo > statspec->cargo_threshold) {
    00641     if (group->num_loading > 0) {
    00642       set = ((cargo - statspec->cargo_threshold) * group->num_loading) / (4096 - statspec->cargo_threshold);
    00643       return group->loading[set];
    00644     }
    00645   } else {
    00646     if (group->num_loaded > 0) {
    00647       set = (cargo * group->num_loaded) / (statspec->cargo_threshold + 1);
    00648       return group->loaded[set];
    00649     }
    00650   }
    00651
    00652   return group->loading[0];
    00653 }
    00654
    00655
    00656 static void NewStationResolver(ResolverObject *res, const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00657 {
    00658   res->GetRandomBits = StationGetRandomBits;
    00659   res->GetTriggers   = StationGetTriggers;
    00660   res->SetTriggers   = StationSetTriggers;
    00661   res->GetVariable   = StationGetVariable;
    00662   res->ResolveReal   = StationResolveReal;
    00663
    00664   res->u.station.st       = st;
    00665   res->u.station.statspec = statspec;
    00666   res->u.station.tile     = tile;
    00667
    00668   res->callback        = CBID_NO_CALLBACK;
    00669   res->callback_param1 = 0;
    00670   res->callback_param2 = 0;
    00671   res->last_value      = 0;
    00672   res->trigger         = 0;
    00673   res->reseed          = 0;
    00674   res->count           = 0;
    00675   res->grffile         = (statspec != NULL ? statspec->grffile : NULL);
    00676 }
    00677
    00678 static const SpriteGroup *ResolveStation(ResolverObject *object)
    00679 {
    00680   const SpriteGroup *group;
    00681   CargoID ctype = CT_DEFAULT_NA;
    00682
    00683   if (object->u.station.st == NULL) {
    00684     /* No station, so we are in a purchase list */
    00685     ctype = CT_PURCHASE;
    00686   } else if (Station::IsExpected(object->u.station.st)) {
    00687     const Station *st = Station::From(object->u.station.st);
    00688     /* Pick the first cargo that we have waiting */
    00689     const CargoSpec *cs;
    00690     FOR_ALL_CARGOSPECS(cs) {
    00691       if (object->u.station.statspec->spritegroup[cs->Index()] != NULL &&
    00692           !st->goods[cs->Index()].cargo.Empty()) {
    00693         ctype = cs->Index();
    00694         break;
    00695       }
    00696     }
    00697   }
    00698
    00699   group = object->u.station.statspec->spritegroup[ctype];
    00700   if (group == NULL) {
    00701     ctype = CT_DEFAULT;
    00702     group = object->u.station.statspec->spritegroup[ctype];
    00703   }
    00704
    00705   if (group == NULL) return NULL;
    00706
    00707   /* Remember the cargo type we've picked */
    00708   object->u.station.cargo_type = ctype;
    00709
    00710   /* Invalidate all cached vars */
    00711   _svc.valid = 0;
    00712
    00713   return SpriteGroup::Resolve(group, object);
    00714 }
    00715
    00716 SpriteID GetCustomStationRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00717 {
    00718   const SpriteGroup *group;
    00719   ResolverObject object;
    00720
    00721   NewStationResolver(&object, statspec, st, tile);
    00722
    00723   group = ResolveStation(&object);
    00724   if (group == NULL || group->type != SGT_RESULT) return 0;
    00725   return group->GetResult() - 0x42D;
    00726 }
    00727
    00728
    00729 SpriteID GetCustomStationGroundRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00730 {
    00731   const SpriteGroup *group;
    00732   ResolverObject object;
    00733
    00734   NewStationResolver(&object, statspec, st, tile);
    00735   if (HasBit(statspec->flags, SSF_SEPARATE_GROUND)) {
    00736     object.callback_param1 = 1; // Indicate we are resolving the ground sprite
    00737   }
    00738
    00739   group = ResolveStation(&object);
    00740   if (group == NULL || group->type != SGT_RESULT) return 0;
    00741   return group->GetResult() - 0x42D;
    00742 }
    00743
    00744
    00745 SpriteID GetCustomStationFoundationRelocation(const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00746 {
    00747   const SpriteGroup *group;
    00748   ResolverObject object;
    00749
    00750   NewStationResolver(&object, statspec, st, tile);
    00751   object.callback_param1 = 2; // Indicate we are resolving the foundation sprites
    00752
    00753   group = ResolveStation(&object);
    00754   if (group == NULL || group->type != SGT_RESULT) return 0;
    00755   return group->GetResult() + GetRegister(0x100);
    00756 }
    00757
    00758
    00759 uint16 GetStationCallback(CallbackID callback, uint32 param1, uint32 param2, const StationSpec *statspec, const BaseStation *st, TileIndex tile)
    00760 {
    00761   const SpriteGroup *group;
    00762   ResolverObject object;
    00763
    00764   NewStationResolver(&object, statspec, st, tile);
    00765
    00766   object.callback        = callback;
    00767   object.callback_param1 = param1;
    00768   object.callback_param2 = param2;
    00769
    00770   group = ResolveStation(&object);
    00771   if (group == NULL) return CALLBACK_FAILED;
    00772   return group->GetCallbackResult();
    00773 }
    00774
    00775
    00783 int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
    00784 {
    00785   uint i;
    00786
    00787   if (statspec == NULL || st == NULL) return 0;
    00788
    00789   for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
    00790     if (st->speclist[i].spec == NULL && st->speclist[i].grfid == 0) break;
    00791   }
    00792
    00793   if (i == MAX_SPECLIST) {
    00794     /* As final effort when the spec list is already full...
    00795      * try to find the same spec and return that one. This might
    00796      * result in slighty "wrong" (as per specs) looking stations,
    00797      * but it's fairly unlikely that one reaches the limit anyways.
    00798      */
    00799     for (i = 1; i < st->num_specs && i < MAX_SPECLIST; i++) {
    00800       if (st->speclist[i].spec == statspec) return i;
    00801     }
    00802
    00803     return -1;
    00804   }
    00805
    00806   if (exec) {
    00807     if (i >= st->num_specs) {
    00808       st->num_specs = i + 1;
    00809       st->speclist = ReallocT(st->speclist, st->num_specs);
    00810
    00811       if (st->num_specs == 2) {
    00812         /* Initial allocation */
    00813         st->speclist[0].spec     = NULL;
    00814         st->speclist[0].grfid    = 0;
    00815         st->speclist[0].localidx = 0;
    00816       }
    00817     }
    00818
    00819     st->speclist[i].spec     = statspec;
    00820     st->speclist[i].grfid    = statspec->grffile->grfid;
    00821     st->speclist[i].localidx = statspec->localidx;
    00822   }
    00823
    00824   return i;
    00825 }
    00826
    00827
    00833 void DeallocateSpecFromStation(BaseStation *st, byte specindex)
    00834 {
    00835   /* specindex of 0 (default) is never freeable */
    00836   if (specindex == 0) return;
    00837
    00838   ETileArea area = ETileArea(st, INVALID_TILE, TA_WHOLE);
    00839   /* Check all tiles over the station to check if the specindex is still in use */
    00840   TILE_AREA_LOOP(tile, area) {
    00841     if (st->TileBelongsToRailStation(tile) && GetCustomStationSpecIndex(tile) == specindex) {
    00842       return;
    00843     }
    00844   }
    00845
    00846   /* This specindex is no longer in use, so deallocate it */
    00847   st->speclist[specindex].spec     = NULL;
    00848   st->speclist[specindex].grfid    = 0;
    00849   st->speclist[specindex].localidx = 0;
    00850
    00851   /* If this was the highest spec index, reallocate */
    00852   if (specindex == st->num_specs - 1) {
    00853     for (; st->speclist[st->num_specs - 1].grfid == 0 && st->num_specs > 1; st->num_specs--) {}
    00854
    00855     if (st->num_specs > 1) {
    00856       st->speclist = ReallocT(st->speclist, st->num_specs);
    00857     } else {
    00858       free(st->speclist);
    00859       st->num_specs = 0;
    00860       st->speclist  = NULL;
    00861       st->cached_anim_triggers = 0;
    00862       return;
    00863     }
    00864   }
    00865
    00866   StationUpdateAnimTriggers(st);
    00867 }
    00868
    00878 bool DrawStationTile(int x, int y, RailType railtype, Axis axis, StationClassID sclass, uint station)
    00879 {
    00880   const StationSpec *statspec;
    00881   const DrawTileSprites *sprites;
    00882   const DrawTileSeqStruct *seq;
    00883   const RailtypeInfo *rti = GetRailTypeInfo(railtype);
    00884   SpriteID relocation;
    00885   SpriteID image;
    00886   SpriteID palette = COMPANY_SPRITE_COLOUR(_local_company);
    00887   uint tile = 2;
    00888
    00889   statspec = GetCustomStationSpec(sclass, station);
    00890   if (statspec == NULL) return false;
    00891
    00892   relocation = GetCustomStationRelocation(statspec, NULL, INVALID_TILE);
    00893
    00894   if (HasBit(statspec->callback_mask, CBM_STATION_SPRITE_LAYOUT)) {
    00895     uint16 callback = GetStationCallback(CBID_STATION_SPRITE_LAYOUT, 0x2110000, 0, statspec, NULL, INVALID_TILE);
    00896     if (callback != CALLBACK_FAILED) tile = callback;
    00897   }
    00898
    00899   if (statspec->renderdata == NULL) {
    00900     sprites = GetStationTileLayout(STATION_RAIL, tile + axis);
    00901   } else {
    00902     sprites = &statspec->renderdata[(tile < statspec->tiles) ? tile + axis : (uint)axis];
    00903   }
    00904
    00905   image = sprites->ground.sprite;
    00906   SpriteID pal = sprites->ground.pal;
    00907   if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
    00908     image += GetCustomStationGroundRelocation(statspec, NULL, INVALID_TILE);
    00909     image += rti->custom_ground_offset;
    00910   } else {
    00911     image += rti->total_offset;
    00912   }
    00913
    00914   DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
    00915
    00916   Point child_offset = {0, 0};
    00917
    00918   foreach_draw_tile_seq(seq, sprites->seq) {
    00919     image = seq->image.sprite;
    00920     if (HasBit(image, SPRITE_MODIFIER_USE_OFFSET)) {
    00921       image += rti->total_offset;
    00922     } else {
    00923       image += relocation;
    00924     }
    00925
    00926     pal = SpriteLayoutPaletteTransform(image, seq->image.pal, palette);
    00927
    00928     if ((byte)seq->delta_z != 0x80) {
    00929       Point pt = RemapCoords(seq->delta_x, seq->delta_y, seq->delta_z);
    00930       DrawSprite(image, pal, x + pt.x, y + pt.y);
    00931
    00932       const Sprite *spr = GetSprite(image & SPRITE_MASK, ST_NORMAL);
    00933       child_offset.x = pt.x + spr->x_offs;
    00934       child_offset.y = pt.y + spr->y_offs;
    00935     } else {
    00936       /* For stations and original spritelayouts delta_x and delta_y are signed */
    00937       DrawSprite(image, pal, x + child_offset.x + seq->delta_x, y + child_offset.y + seq->delta_y);
    00938     }
    00939   }
    00940
    00941   return true;
    00942 }
    00943
    00944
    00945 const StationSpec *GetStationSpec(TileIndex t)
    00946 {
    00947   if (!IsCustomStationSpecIndex(t)) return NULL;
    00948
    00949   const BaseStation *st = BaseStation::GetByTile(t);
    00950   uint specindex = GetCustomStationSpecIndex(t);
    00951   return specindex < st->num_specs ? st->speclist[specindex].spec : NULL;
    00952 }
    00953
    00954
    00955 /* Check if a rail station tile is traversable.
    00956  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
    00957 bool IsStationTileBlocked(TileIndex tile)
    00958 {
    00959   const StationSpec *statspec = GetStationSpec(tile);
    00960
    00961   return statspec != NULL && HasBit(statspec->blocked, GetStationGfx(tile));
    00962 }
    00963
    00964 /* Check if a rail station tile is electrifiable.
    00965  * XXX This could be cached (during build) in the map array to save on all the dereferencing */
    00966 bool IsStationTileElectrifiable(TileIndex tile)
    00967 {
    00968   const StationSpec *statspec = GetStationSpec(tile);
    00969
    00970   return
    00971     statspec == NULL ||
    00972     HasBit(statspec->pylons, GetStationGfx(tile)) ||
    00973     !HasBit(statspec->wires, GetStationGfx(tile));
    00974 }
    00975
    00976 void AnimateStationTile(TileIndex tile)
    00977 {
    00978   const StationSpec *ss = GetStationSpec(tile);
    00979   if (ss == NULL) return;
    00980
    00981   const BaseStation *st = BaseStation::GetByTile(tile);
    00982
    00983   uint8 animation_speed = ss->anim_speed;
    00984
    00985   if (HasBit(ss->callback_mask, CBM_STATION_ANIMATION_SPEED)) {
    00986     uint16 callback = GetStationCallback(CBID_STATION_ANIMATION_SPEED, 0, 0, ss, st, tile);
    00987     if (callback != CALLBACK_FAILED) animation_speed = Clamp(callback & 0xFF, 0, 16);
    00988   }
    00989
    00990   if (_tick_counter % (1 << animation_speed) != 0) return;
    00991
    00992   uint8 frame      = GetStationAnimationFrame(tile);
    00993   uint8 num_frames = ss->anim_frames;
    00994
    00995   bool frame_set_by_callback = false;
    00996
    00997   if (HasBit(ss->callback_mask, CBM_STATION_ANIMATION_NEXT_FRAME)) {
    00998     uint32 param = HasBit(ss->flags, SSF_CB141_RANDOM_BITS) ? Random() : 0;
    00999     uint16 callback = GetStationCallback(CBID_STATION_ANIM_NEXT_FRAME, param, 0, ss, st, tile);
    01000
    01001     if (callback != CALLBACK_FAILED) {
    01002       frame_set_by_callback = true;
    01003
    01004       switch (callback & 0xFF) {
    01005         case 0xFF:
    01006           DeleteAnimatedTile(tile);
    01007           break;
    01008
    01009         case 0xFE:
    01010           frame_set_by_callback = false;
    01011           break;
    01012
    01013         default:
    01014           frame = callback & 0xFF;
    01015           break;
    01016       }
    01017
    01018       /* If the lower 7 bits of the upper byte of the callback
    01019        * result are not empty, it is a sound effect. */
    01020       if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
    01021     }
    01022   }
    01023
    01024   if (!frame_set_by_callback) {
    01025     if (frame < num_frames) {
    01026       frame++;
    01027     } else if (frame == num_frames && HasBit(ss->anim_status, 0)) {
    01028       /* This animation loops, so start again from the beginning */
    01029       frame = 0;
    01030     } else {
    01031       /* This animation doesn't loop, so stay here */
    01032       DeleteAnimatedTile(tile);
    01033     }
    01034   }
    01035
    01036   SetStationAnimationFrame(tile, frame);
    01037   MarkTileDirtyByTile(tile);
    01038 }
    01039
    01040
    01041 static void ChangeStationAnimationFrame(const StationSpec *ss, const BaseStation *st, TileIndex tile, uint16 random_bits, StatAnimTrigger trigger, CargoID cargo_type)
    01042 {
    01043   uint16 callback = GetStationCallback(CBID_STATION_ANIM_START_STOP, (random_bits << 16) | Random(), (uint8)trigger | (cargo_type << 8), ss, st, tile);
    01044   if (callback == CALLBACK_FAILED) return;
    01045
    01046   switch (callback & 0xFF) {
    01047     case 0xFD: /* Do nothing. */         break;
    01048     case 0xFE: AddAnimatedTile(tile);    break;
    01049     case 0xFF: DeleteAnimatedTile(tile); break;
    01050     default:
    01051       SetStationAnimationFrame(tile, callback);
    01052       AddAnimatedTile(tile);
    01053       break;
    01054   }
    01055
    01056   /* If the lower 7 bits of the upper byte of the callback
    01057    * result are not empty, it is a sound effect. */
    01058   if (GB(callback, 8, 7) != 0) PlayTileSound(ss->grffile, GB(callback, 8, 7), tile);
    01059 }
    01060
    01061 void StationAnimationTrigger(const BaseStation *st, TileIndex tile, StatAnimTrigger trigger, CargoID cargo_type)
    01062 {
    01063   /* List of coverage areas for each animation trigger */
    01064   static const TriggerArea tas[] = {
    01065     TA_TILE, TA_WHOLE, TA_WHOLE, TA_PLATFORM, TA_PLATFORM, TA_PLATFORM, TA_WHOLE
    01066   };
    01067
    01068   /* Get Station if it wasn't supplied */
    01069   if (st == NULL) st = BaseStation::GetByTile(tile);
    01070
    01071   /* Check the cached animation trigger bitmask to see if we need
    01072    * to bother with any further processing. */
    01073   if (!HasBit(st->cached_anim_triggers, trigger)) return;
    01074
    01075   uint16 random_bits = Random();
    01076   ETileArea area = ETileArea(st, tile, tas[trigger]);
    01077
    01078   /* Check all tiles over the station to check if the specindex is still in use */
    01079   TILE_AREA_LOOP(tile, area) {
    01080     if (st->TileBelongsToRailStation(tile)) {
    01081       const StationSpec *ss = GetStationSpec(tile);
    01082       if (ss != NULL && HasBit(ss->anim_triggers, trigger)) {
    01083         CargoID cargo;
    01084         if (cargo_type == CT_INVALID) {
    01085           cargo = CT_INVALID;
    01086         } else {
    01087           cargo = GetReverseCargoTranslation(cargo_type, ss->grffile);
    01088         }
    01089         ChangeStationAnimationFrame(ss, st, tile, random_bits, trigger, cargo);
    01090       }
    01091     }
    01092   }
    01093 }
    01094
    01099 void StationUpdateAnimTriggers(BaseStation *st)
    01100 {
    01101   st->cached_anim_triggers = 0;
    01102
    01103   /* Combine animation trigger bitmask for all station specs
    01104    * of this station. */
    01105   for (uint i = 0; i < st->num_specs; i++) {
    01106     const StationSpec *ss = st->speclist[i].spec;
    01107     if (ss != NULL) st->cached_anim_triggers |= ss->anim_triggers;
    01108   }
    01109 }