# newgrf_station.cpp

Go to the documentation of this file.

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