# newgrf_station.cpp

Go to the documentation of this file.

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